John
John

Reputation: 85

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?

Upvotes: 6

Views: 186

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 12

Related Questions