0

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
Jim Fell
  • 13,750
  • 36
  • 127
  • 202
  • 1
    Have you tried to do a simple System.out.println(strVal); Just to see what is stored in strVal. By the way why are you doing this strVal += '\0'; in java? I dont think you need that in java take it out and see if it solves the problem. – user3591111 Apr 10 '19 at 16:06
  • 3
    Why do you append a '\0' to the strVal? – mayamar Apr 10 '19 at 16:08
  • And why do you use j as index in buffer[] in the loop? Shouldn' that be i? – mayamar Apr 10 '19 at 16:09
  • I think he use the j because he doesnt want the full word he only whants the word store between the possition 9 and 17. – user3591111 Apr 10 '19 at 16:11
  • 1
    What do you mean by "byte packed"? Your code seems to imply that the bytes are simply the ASCII bytes, which is not really "packed", just encoded with a single-byte character set, so use [**`new String(buffer, 9, 8, StandardCharsets.US_ASCII)`**](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-int-int-java.nio.charset.Charset-) to convert 8 bytes starting at index 9 to a string. – Andreas Apr 10 '19 at 16:19

2 Answers2

0

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

Jim Fell
  • 13,750
  • 36
  • 127
  • 202
-1

Don't append 0, use i in the loop:

    byte[] buffer = new byte[20];
    /* ... buffer is loaded ... */

    String strVal = "";
    for (int i = 0; i < 8; i++) {
        strVal += (char) buffer[i];
    }
mayamar
  • 412
  • 3
  • 5
  • You can also look at this answer that explain very well why you dont need \0 in the string. https://stackoverflow.com/questions/26558741/what-does-strnewlength-0-mean – user3591111 Apr 10 '19 at 16:12
  • 1
    Why are you assuming that when OP specifically wrote code to extract string starting at index 9, OP didn't mean it? Your answer reads like "use i in the loop" is the solution to "Don't append 0", and that is certainly not the case. To not append 0, simply remove that statement that is *after* the loop, which is the statement that explicitly adds a 0. – Andreas Apr 10 '19 at 16:23