DoubleYou
DoubleYou

Reputation: 1087

Dynamically setting multiple bits in uint

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

Answers (4)

SACHIN DHIVARE
SACHIN DHIVARE

Reputation: 115

Here is the more generic solution for your question

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

Hillel
Hillel

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

Adarsh
Adarsh

Reputation: 893

I hope this should work,

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

Upvotes: 0

user3386109
user3386109

Reputation: 34829

How about

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

Of course, this only works if bitloc <= 30.

Upvotes: 0

Related Questions