What does AND 0xFF do?

后端 未结 7 1244
我在风中等你
我在风中等你 2020-12-23 02:12

In the following code:

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

What is the purpose of &0xFF? Because other somes

7条回答
  •  抹茶落季
    2020-12-23 02:29

    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.

提交回复
热议问题