Doesn't bitwise-ANDing with 0xff essentially mean getting the same value back, for that matter, in this code?
byte[] packet = reader.readPacket();
short sh;
sh = packet[1];
sh &= 0xFF;
System.out.print(sh+" ");
Weirdly, I get a -1 if that ANDing is not included but a 255 when included Could someone explain the reason?
As I see it 0xff is just 1111 1111. Isn't it?
In general, the & 0xff operation provides us with a simple way to extract the lowest 8 bits from a number. We can actually use it to extract any 8 bits we need because we can shift right any of the 8 bits we want to be the lowest bits. Then, we can extract them by applying the & 0xff operation.
Bitwise operations are worth studying because they have many applications. It is not their main use to substitute arithmetic operations. Cryptography, computer graphics, hash functions, compression algorithms, and network protocols are just some examples where bitwise operations are extremely useful.
So, for example, binary 10000010 represents decimal 130 (128+2) if it's unsigned, but -126 (-128+2) if that same value is signed. Negative one is 0xff, since 64+32+16+8+4+2+1==127.
0xFF is 11111111 in binary or 255 in decimal.
Yes, 0xff
is just 1111 1111
. But this is attempting to display the unsigned byte value, even though in Java byte
s are signed. The value 0xff
is -1
for a signed byte
, but it's 255
in a short
.
When a byte
value of 0xff
is read, printing the value would yield -1
. So it's assigned to a short
which has a bigger range and can store byte
values that would normally overflow to be a negative number as a byte
as a positive integer, e.g. 144 as a byte
is 0x90
, or -112, but it can be properly stored as 144
as a short
.
So the byte
value of -1
is assigned to a short
. But what does that do? A primitive widening conversion takes place, and negative values are sign-extended. So 1111 1111
becomes 11111111 11111111
, still -1
, but this time as a short
.
Then the bitmask 0xff
(00000000 11111111
) is used to get the last 8 bits out again:
-1: 11111111 1111111
0xFF: 00000000 1111111
======================
255: 00000000 1111111
It's just a way to get the unsigned byte
value, by converting it to short
and then masking out the original bits from the byte
, to display it as an unsigned value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With