简体   繁体   中英

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 2 byte value. This code does the job just fine but prior to testing i had it written like this

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

and the result was not right. My question is why is 0xff necessary in this scenario?

The 0xff is necessary because of a confluence of two factors:

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

The result is that if the high-order bit of content[11] was set, it will be sign-extended to a negative int value. You need to then & this with 0xff to return it to a (positive) byte value. Otherwise when you | it with the result of content[12]<<8 , the high-order byte will be all 1s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM