What is the best way to construct a bit mask in C with m set bits preceded by k unset bits, and followed by n unset bits:
Whilst the top answers are simple and effective they don't set the MSB for the case when n=0 and m=31:
~(~0 << 31) << 0 = 0111 1111 1111 1111 1111 1111 1111 1111
((1 << 31)-1) << 0 = 0111 1111 1111 1111 1111 1111 1111 1111
My suggestion for a 32-bit unsigned word (which is ugly and has a branch) looks like this:
unsigned int create_mask(unsigned int n,unsigned int m) {
// 0 <= start_bit, end_bit <= 31
return (m - n == 31 ? 0xFFFFFFFF : ((1 << (m-n)+1)-1) << n);
}
This actually gets the bits in the range [m,n] (closed interval) so create_mask(0,0) will return a mask for the first bit (bit 0) and create_mask(4,6) returns a mask for bits 4 to 6 i.e ... 00111 0000.