For any integer n, fewer bits in a word, the required mask is:
const unsigned int mask = (1u << n) - 1;
No loop required.
Simple function:
unsigned int set_lsbs(unsigned int n)
{
return (1u << n) - 1;
}
The top ten results:
0: 0x0
1: 0x1
2: 0x3
3: 0x7
4: 0xf
5: 0x1f
6: 0x3f
7: 0x7f
8: 0xff
9: 0x1ff
Note: the syntax is 0xb00011111not a binary literal, that 'b' is simply interpreted as a hexadecimal digit.
source
share