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

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

    0x2F is 0010 1111 in binary - this should be 0x3f, which is 0011 1111 in binary and which has the 6 least-significant bits set.

    Similarly, 0x1FFFF is 0001 1111 1111 1111 1111 in binary, which has the 17 least-significant bits set.

    A "mask" is a value that is intended to be combined with another value using a bitwise operator like &, | or ^ to individually set, unset, flip or leave unchanged the bits in that other value.

    For example, if you combine the mask 0x2F with some value n using the & operator, the result will have zeroes in all but the 6 least significant bits, and those 6 bits will be copied unchanged from the value n.

    In the case of an & mask, a binary 0 in the mask means "unconditionally set the result bit to 0" and a 1 means "set the result bit to the input value bit". For an | mask, an 0 in the mask sets the result bit to the input bit and a 1 unconditionally sets the result bit to 1, and for an ^ mask, an 0 sets the result bit to the input bit and a 1 sets the result bit to the complement of the input bit.

提交回复
热议问题