How to create mask with least significat bits set to 1 in C

sebi picture sebi · Sep 14, 2012 · Viewed 34.9k times · Source

Can someone please explain this function to me?

A mask with the least significant n bits set to 1.

Ex:

n = 6 --> 0x2F, n = 17 --> 0x1FFFF // I don't get these at all, especially how n = 6 --> 0x2F

Also, what is a mask?

Answer

Jerry Coffin picture Jerry Coffin · Sep 14, 2012

The usual way is to take a 1, and shift it left n bits. That will give you something like: 00100000. Then subtract one from that, which will clear the bit that's set, and set all the less significant bits, so in this case we'd get: 00011111.

A mask is normally used with bitwise operations, especially and. You'd use the mask above to get the 5 least significant bits by themselves, isolated from anything else that might be present. This is especially common when dealing with hardware that will often have a single hardware register containing bits representing a number of entirely separate, unrelated quantities and/or flags.