Search code examples
c++cgccbitwise-operators

Set last `n` bits in unsigned int


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);. Function should handle each n from 0 to 32.

Especially value n==32 should be handled.


Solution

  • If you meant the least-significant n bits:

    ((uint32_t)1 << n) - 1
    

    On most architectures, this won't work if n is 32, so you may have to make a special case for that:

    n == 32 ? 0xffffffff : (1 << n) - 1
    

    On a 64-bit architecture, a (probably) faster solution is to cast up then down:

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

    In fact, this might even be faster on a 32-bit architecture since it avoids branching.