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?
A
byte
has the range of -128 to 127. This means some values are negative. This is all the values where the top bit is set. So(byte) 0xFF
is -1. When you use sign extension to make it a signed short, it becomes(short) 0xFFFF
which is -1 as a short. When you mask it, it chop off the extended bits and you treat the byte as if it where unsigned.You don't get -1 unless your code is different to what you have in the question.
prints
(Assuming two's complement everywhere) Two things:
0xff
in a byte is equal to -1.byte
to ashort
), the value is kept. So,sh = packet[1]
would setsh
to-1
, which is0xffff
.The thing with point #2 is that the "extra" bits get padded with 1s to keep the value whenever the original value is negative. The idea behind ANDing with
0xff
is thatsh
now contains0x00ff
, with those "extra" 1s now removed.Yes,
0xff
is just1111 1111
. But this is attempting to display the unsigned byte value, even though in Javabyte
s are signed. The value0xff
is-1
for a signedbyte
, but it's255
in ashort
.When a
byte
value of0xff
is read, printing the value would yield-1
. So it's assigned to ashort
which has a bigger range and can storebyte
values that would normally overflow to be a negative number as abyte
as a positive integer, e.g. 144 as abyte
is0x90
, or -112, but it can be properly stored as144
as ashort
.So the
byte
value of-1
is assigned to ashort
. But what does that do? A primitive widening conversion takes place, and negative values are sign-extended. So1111 1111
becomes11111111 11111111
, still-1
, but this time as ashort
.Then the bitmask
0xff
(00000000 11111111
) is used to get the last 8 bits out again:It's just a way to get the unsigned
byte
value, by converting it toshort
and then masking out the original bits from thebyte
, to display it as an unsigned value.