Java bitwise operation

I have this line of code

int b1 = 0xffff & (content[12]<<8 | 0xff & content[11]); 

I have a bytearray (content []) in little endian and need to recreate a value of 2 bytes. This code does a great job, but before testing, I wrote it as

 int b1 = 0xffff & (content[12]<<8 | content[11]); 

and the result was wrong. My question is, why is 0xff necessary in this case?

+6
source share
1 answer

0xff necessary due to the merger of two factors:

  • All integer types in Java are signed
  • All bitwise operators push their arguments to int (or long , if necessary) before acting.

As a result, if the high-order bit content[11] been set, it will be decrypted by the icon to a negative value of int . Then you need & with 0xff to return its (positive) byte value. Otherwise, when you | with the result content[12]<<8 , the high byte will be 1 s.

+12
source

All Articles