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

前端 未结 6 1934
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 06:42

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:05

    I believe your first example should be 0x3f.

    0x3f is hexadecimal notation for the number 63 which is 111111 in binary, so that last 6 bits (the least significant 6 bits) are set to 1.

    The following little C program will calculate the correct mask:

    #include 
    #include 
    
    int mask_for_n_bits(int n)
    {
        int mask = 0;
    
        for (int i = 0; i < n; ++i)
            mask |= 1 << i;
    
        return mask;
    }
    
    int main (int argc, char const *argv[])
    {
        printf("6: 0x%x\n17: 0x%x\n", mask_for_n_bits(6), mask_for_n_bits(17));
        return 0;
    }
    

提交回复
热议问题