What does value & 0xff do in Java?

dagronlund picture dagronlund · Jul 8, 2012 · Viewed 112.6k times · Source

I have the following Java code:

byte value = 0xfe; // corresponds to -2 (signed) and 254 (unsigned)
int result = value & 0xff;

The result is 254 when printed, but I have no idea how this code works. If the & operator is simply bitwise, then why does it not result in a byte and instead an integer?

Answer

Ted Hopp picture Ted Hopp · Jul 8, 2012

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.