Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set bit until a certain index

How do I set the bits of an integer to 1 until a certain index? I can only think of either computing the total value as an unsigned integer or iterating in a loop:

//index in question
int index = 20;
uint32_t bitmask = 1;
for (int i = 0; i < index; i++){
    bitmask = (bitmask << 1) + 1;
}

Is there another way to define this bitmask without computation? Thanks!


1 Answers

((uint32_t) 2 << index) - 1.

Unlike ((uint32_t) 1 << index+1) - 1, this will not overflow when index is 31. (If the shift width equals or exceeds the number of bits in the type, the behavior is not defined by the C standard.)

like image 67
Eric Postpischil Avatar answered Feb 22 '26 09:02

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!