Set last `n` bits in unsigned int

后端 未结 9 1288
小蘑菇
小蘑菇 2020-12-17 15:30

How to set (in most elegant way) exactly n least significant bits of uint32_t? That is to write a function void setbits(uint32_t *x, int n);<

9条回答
  •  时光说笑
    2020-12-17 16:07

    If n is zero then no bits should be set based on the question.

    const uint32_t masks[32] = {0x1, 0x3, 0x7, ..., 0xFFFFFFFF};
    
    void setbits(uint32_t *x, int n)
    {
        if ( (n > 0) && (n <= 32) )
        {
            *x |= masks[--n];
        }
    }
    

提交回复
热议问题