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.
To isolate any set of bits, apply an AND mask. If you want the last X bits of a value, there is a simple trick that can be used. unsigned mask; mask = (1 << X) - 1; lastXbits = value & mask; If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...
range = (((1 << (l - 1)) - 1) ^ ((1 << (r)) - 1)); 2. Now, perform "n = n | range". This will set the bits in the range from l to r in n.
to set the bit n of num (for instance num |= (1 << 0); sets the bit 0 ). To set (clear) multiple bits you have just to OR ( AND ) the num with the appropriate constant. num &= ~0xFF; clears the same bits.
Here's a method that doesn't require any arithmetic:
~(~0u << 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With