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);<
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.
const uint32_t masks[33] = {0x0, 0x1, 0x3, 0x7 ...
void setbits(uint32_t *x, int n)
{
*x |= masks[n];
}
If you mean the most significant n bits:
-1 ^ ((1 << (32 - n)) - 1)
((((1 << (n - 1)) - 1) << 1) | 1)
Set last n bits. n must be > 0. Work with n = 32.
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)
Here's a method that doesn't require any arithmetic:
~(~0u << n)