I am really confused, but cannot to do simple task as it seems:
I simply need to set number of bits in byte.
For example:
I need 5 bits set. So I need 0xb00011111
.
Is it possible to do this without loop?
Also I'd not like to write lot of #defines
too.
For any integer n
less than the number of bits in the word, the mask you need is:
const unsigned int mask = (1u << n) - 1;
No loop required.
A simple function using this:
unsigned int set_lsbs(unsigned int n)
{
return (1u << n) - 1;
}
The ten first results are:
0: 0x0
1: 0x1
2: 0x3
3: 0x7
4: 0xf
5: 0x1f
6: 0x3f
7: 0x7f
8: 0xff
9: 0x1ff
Note: the syntax 0xb00011111
is not not a binary literal, that 'b' is simply interpreted as a hex digit.
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