Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise-ANDing with 0xff is important?

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?

like image 833
Shashank Sabniveesu Avatar asked Sep 27 '13 23:09

Shashank Sabniveesu


People also ask

Why do we need to and with 0xff?

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.

Are bitwise operations important?

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.

Is 0xff positive or negative?

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.

What is 0xff in assembly language?

0xFF is 11111111 in binary or 255 in decimal.


1 Answers

Yes, 0xff is just 1111 1111. But this is attempting to display the unsigned byte value, even though in Java bytes 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.

like image 118
rgettman Avatar answered Oct 23 '22 12:10

rgettman