Search code examples
javastring-comparison

How to compare byte-packed string in Java?


My Java application has a byte-packed String object that is assembled from remote data received that over an external connection. The string is assembled, like so:

byte[] buffer = new byte[20];
/* ... buffer is loaded ... */
int j = 9;
String strVal = "";
for( i=0; i<8; i++ )
{
    strVal += (char)buffer[j++];
}
strVal += '\0';

Later, I need to validate the received data, but when I attempt the following it returns false. Both the data in the buffer and the contents of strVal (at least as what I can view in the debugger) are what I would expect. Any ideas?

return strVal.equals("STR GOOD"); // evaluates as false when should be true

Solution

  • Removing the '\0' from the end of the byte array resolved the problem.