Set last `n` bits in unsigned int

后端 未结 9 1326
小蘑菇
小蘑菇 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:01

    The other answers don't handle the special case of n == 32 (shifting by greater than or equal to the type's width is UB), so here's a better answer:

    (uint32_t)(((uint64_t)1 << n) - 1)
    

    Alternatively:

    (n == 32) ? 0xFFFFFFFF : (((uint32_t)1 << n) - 1)
    

提交回复
热议问题