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


What about

bits |= (2 << bitloc) - 1;

      



Of course, this only works if bitloc <= 30

.

0


source


I hope this works,

bits |= ~((~0)<<(bitloc + 1))

      

0


source


Here is a more general solution to your question

Suppose you want to set the "N" bit from a specific "P" position from the MSB to the LSB at a specified value "X". Then the solution will be


X = X | ((~ (~ 0 <N)) <((P + 1) - N));

0


source







All Articles