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!
((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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With