I’m catching a serial stream and trying to take two bytes and turn them into a signed short in Processing. The code is simple but there is an occasional glitch when I combine the two bytes. This is the code with lots of internal prints.
println(hex(inBuffer[i-2]) + " " + hex(inBuffer[i-3]));
x = inBuffer[i-2];
println(hex(x));
x <<= 8;
println(hex(x));
println(hex(inBuffer[i-3]));
x = (short) (x | inBuffer[i-3]);
println(hex(x));
for (int j=15; j>=0; j--){
print(((1<<j) & x)>>j);
}
println("");
println(x);
println("");
Sometimes I get this, which is great :
41 27
00000041
00004100
27
00004127
0100000100100111
16679
Which is great! But sometimes I get this :
41 A7
00000041
00004100
A7
FFFFFFA7
1111111110100111
-89
Which is not great. I don’t know why (0xA7 | 0x004100) = 0xFFFFFFA7.
Any thoughts?
Here’s a hint: A7 is a number > 128. And Java treats bytes as signed.
You need to add some foo & 255 into your code.
e.g. Check out the source code for DataInputStream.readLong().