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

前端 未结 6 1606
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 06:43

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 ge

6条回答
  •  滥情空心
    2021-02-13 07:04

    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.

提交回复
热议问题