You appear to be confused.
There is no point in your code. taking any number, calculating that & 0xFF
, and then storing it in a byte, is always a noop - it does nothing.
You additionally get an error because &
inherently always produces at least an int
(it'll upcast anything smaller to match), so you're trying to assign an int to a byte.
What are you trying to accomplish?
"I want to have my byte be unsigned"!
No can do. Java doesn't have unsigned bytes. A java byte is signed. Period. It can hold a value between -128 and +127. For calculation purposes, -128 and 255 are identical (they are both the bit sequence 1111 1111
- in hex, 0xFF
, and they act identically under all relevant arithmetic, though it does get tricky when converting them to another numeric type int
).
"I just want to store 255"!
Then use int
. This is where most & 0xFF
you'll ever see in java code comes from: When you have a byte value which java inherently treats as signed, but you wish to treat it as unsigned and, therefore (given that in java bytes can't do that), you want to upcast it to an int, containing the unsigned representation. This is how to do that:
int x = y & 0xFF;
Where y
is any byte.
You presumably saw this somewhere and are now trying to apply it, but assigning the result of y & 0xFF
to a byte
doesn't mean anything. You'd assign it to an int
variable, or just use it as expression in a further calculation (y & 0xFF
is an int
- make sure you add the appropriate parentheses, &
has perhaps unexpected precedence).
int x = 36;
byte b1 = ((byte) x) & ((byte) 0xff);
Every imaginable way of this actually working would mean that b1
is... still 36.