I have written the following code but findbugs is shwowing this error: BIT_ADD_OF_SIGNED_BYTE. I tried a lot but may be I am not getting the concept of left shift correctly.
void problem() {
byte [] byteArray = {1, 2, 3, 4, 5};
int localOne = 0;
for(int i = 0; i < 4; i++) {
localOne = (localOne<<8) + byteArray[i];
}
}
You’r doing the shift correctly, your (possible) error is when adding a signed
byteto anintBecause of sign extension you need to do this:
Say you have the byte
80(hex), which is1000 0000(binary), this is-128(decimal) because of the two’s complement representation. Now, when adding it to anintit first gets converted to anint. The resultingintis not(binary) it will be
(binary) because of sign extension. To get the first, you have to apply a bitwise and with
0xFFwich is this in binary: