What does AND 0xFF do?

Muis picture Muis · Feb 5, 2013 · Viewed 103.9k times · Source

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?

Answer

John Colanduoni picture John Colanduoni · Feb 5, 2013

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.