Dynamically setting multiple bits in uint
I have unsigned int
one that contains a series of bits and a specific bit location.
Now I want to set all bits to 1 from this bit location "down". How can this be achieved simply without a loop?
Example:
unsigned int bitloc=2;
unsigned int bits=??; //must become 0000 0111
unsigned int bitloc=4;
unsigned int bits=??; //must become 0001 1111
An equivalent function that produces the result:
bits=0;
for (unsigned int i=0; i<=bitloc; i++)
bits|=1<<i;
+3
source to share
4 answers
What about?
unsigned int Mask = 0xffffffff;
bits = Mask >> (31 - bitloc);
like in your example bitloc is 2: The mask is a binary number of them, then we shift it 29 times, effectively adding 29 zeros to the left, leaving only bit with zero bit one and bit two as ones.
0xffffffff → 29 = 0x00000007 = 000 ... 0111
+2
source to share