Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does AND 0xFF do?

In the following code:

short = ((byte2 << 8) | (byte1 & 0xFF)) 

What is the purpose of &0xFF? Because other somestimes I see it written as:

short = ((byte2 << 8) | byte1) 

And that seems to work fine too?

like image 584
Maestro Avatar asked Feb 05 '13 17:02

Maestro


People also ask

What does 0xff mean in C++?

0xff means "the hexadecimal number ff " - in other words, the integer 255 , which has the binary representation 00000000000000000000000011111111 (when using 32-bit integers). The & operator performs a bitwise AND operation.

What is 0xff byte?

The signed byte 0xff represents the value -1 . This is because Java uses two's complement to represent signed values. The signed byte 0xff represents -1 because its most significant bit is 1 (so therefore it represents a negative value) and its value is -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1 .

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 Arduino?

Well, 0xff is the hexadecimal number FF which has a integer value of 255. And the binary representation of FF is 00000000000000000000000011111111 (under the 32-bit integer). The & operator performs a bitwise AND operation.


2 Answers

if byte1 is an 8-bit integer type then it's pointless - if it is more than 8 bits it will essentially give you the last 8 bits of the value:

    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1  &  0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1     -------------------------------     0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 
like image 63
D Stanley Avatar answered Oct 04 '22 05:10

D Stanley


Anding an integer with 0xFF leaves only the least significant byte. For example, to get the first byte in a short s, you can write s & 0xFF. This is typically referred to as "masking". If byte1 is either a single byte type (like uint8_t) or is already less than 256 (and as a result is all zeroes except for the least significant byte) there is no need to mask out the higher bits, as they are already zero.

See tristopiaPatrick Schlüter's answer below when you may be working with signed types. When doing bitwise operations, I recommend working only with unsigned types.

like image 37
John Colanduoni Avatar answered Oct 04 '22 06:10

John Colanduoni