Java – Unsigned Bytes in Java

bytejava

Bytes in Java are signed by default. I see on other posts that a workaround to have unsigned bytes is something similar to that: int num = (int) bite & 0xFF

Could someone please explain to me why this works and converts a signed byte to an unsigned byte and then its respective integer? ANDing a byte with 11111111 results in the same byte – right?

Best Answer

A typecast has a higher precedence than the & operator. Therefore you're first casting to an int, then ANDing in order to mask out all the high-order bits that are set, including the "sign bit" of the two's complement notation which java uses, leaving you with just the positive value of the original byte. E.g.:

let byte x = 11111111 = -1
then (int) x = 11111111 11111111 11111111 11111111
and x & 0xFF = 00000000 00000000 00000000 11111111 = 255

and you've effectively removed the sign from the original byte.