What’s the use of “& 0xff” in programming?

When I strated out, I was really confused about bit shift and hexadecimal number and binary. This is a good example how confusing it could get sometimes. Occasionally you see this in the code, for exmaple in C++:

byte a = ( b >>  8) & 0xff; // b is an integer

Okay, I know what “>> 8” means, we are shifting variable “b” to the right by 8 bits. But, what the heck is “& 0xff” doing there?

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. a & b will give you an integer with a bit pattern that has a 0 in all positions where b has a 0, while in all positions where b has a 1, the corresponding bit value froma is used (this also goes the other way around). For example, the bitwise AND of 10110111 and00001101 is 00000101.

In a nutshell, “& 0xff” effectively masks the variable so it leaves only the value in the last 8 bits, and ignores all the rest of the bits.

It’s seen most in cases like when trying to transform color values from a special format to standard RGB values (which is 8 bits long).

5 thoughts on “What’s the use of “& 0xff” in programming?

  1. bit_shift

    Forgive me, but isn’t it >> a right shift, because you know it point right and move the bits to the right, and << is the left shift?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you Robot? *

I don't look at blog comments very often (maybe once or twice a week), so if you have any questions related to multirotor please post it on this forum IntoFPV.com... You're likely to get a response from me faster on there.