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

前端 未结 6 1616
被撕碎了的回忆
被撕碎了的回忆 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:06

    First, for those who only want the code to create the mask:

    uint64_t bits = 6;
    uint64_t mask = ((uint64_t)1 << bits) - 1;
    # Results in 0b111111 (or 0x03F)
    

    For those who want to know what a mask is:

    A mask is usually a name for value that we use to manipulate other values using bitwise operations such as AND, OR, XOR, etc.

    Short masks are usually represented in binary, where we can explicitly see all the bits that are set to 1.

    Longer masks are usually represented in hexadecimal, that is really easy to read once you get a hold of it.

    You can read more about bitwise operations in C here go you get a better grasp of the material.

提交回复
热议问题