What does AND 0xFF do?

47

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?

This question is tagged with c bit-manipulation bitwise-operators bit-shift

~ Asked on 2013-02-05 17:14:59

The Best Answer is


39

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.

~ Answered on 2013-02-05 17:16:44


36

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

~ Answered on 2013-02-05 17:18:59


Most Viewed Questions: