Reputation: 1087
I have an unsigned int
that holds a series of bits, and a certain bit location.
Now I want to set all bits to 1 from that bit location 'downwards'. 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
Equivalent function that creates the result:
bits=0;
for (unsigned int i=0; i<=bitloc; i++)
bits|=1<<i;
Upvotes: 3
Views: 708
Reputation: 115
Lets say you want to set "N" bits from a specific position "P" from M.S.B. towards LSB in a given value "X". Then the solution will be
X = X | ((~(~0 << N)) << ((P + 1) - N));
Upvotes: 0
Reputation: 331
How about?
unsigned int Mask = 0xffffffff;
bits = Mask >> (31 - bitloc);
as in your example bitloc is 2: Mask is a binary number of ones then we shift right it 29 time effectively adding 29 zeros from the left leaving only bit zero bit one and bit two as ones.
0xffffffff >> 29 = 0x00000007=000...0111
Upvotes: 2
Reputation: 34829
How about
bits |= (2 << bitloc) - 1;
Of course, this only works if bitloc <= 30
.
Upvotes: 0