6

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?

1
  • Because bytes are interpreted as signed integers, and this means, for example, that (byte) 0x80 gets (int) 0xffffff80. This is called sign extension. Commented Apr 4, 2013 at 18:26

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx for the reply! I would not have guessed content[11] would be casted to int with high-order bit set. I thought when i combine two values with OR they would be used AS ARE on the bit level. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.