Set last `n` bits in unsigned int

后端 未结 9 1289
小蘑菇
小蘑菇 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 15:47

    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.

    0 讨论(0)
  • 2020-12-17 15:52
    const uint32_t masks[33] = {0x0, 0x1, 0x3, 0x7 ...
    
    void setbits(uint32_t *x, int n)
    {
       *x |= masks[n];
    }
    
    0 讨论(0)
  • 2020-12-17 15:54

    If you mean the most significant n bits:

    -1 ^ ((1 << (32 - n)) - 1)
    
    0 讨论(0)
  • 2020-12-17 15:58
    ((((1 << (n - 1)) - 1) << 1) | 1)
    

    Set last n bits. n must be > 0. Work with n = 32.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-17 16:07

    Here's a method that doesn't require any arithmetic:

    ~(~0u << n)
    
    0 讨论(0)
提交回复
热议问题