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?
It sets
resultto the (unsigned) value resulting from putting the 8 bits ofvaluein the lowest 8 bits ofresult.The reason something like this is necessary is that
byteis a signed type in Java. If you just wrote:then
resultwould end up with the valueff ff ff feinstead of00 00 00 fe. A further subtlety is that the&is defined to operate only onintvalues1, so what happens is:valueis promoted to anint(ff ff ff fe).0xffis anintliteral (00 00 00 ff).&is applied to yield the desired value forresult.(The point is that conversion to
inthappens before the&operator is applied.)1Well, not quite. The
&operator works onlongvalues as well, if either operand is along. But not onbyte. See the Java Language Specification, sections 15.22.1 and 5.6.2.