How does this code work to Find the next highest power of 2 for any given number [>1] for 32 bit integer?
n--;
n = n | n>>1;
n = n | n>>2;
n = n | n>>4;
n = n | n>>8;
n = n | n>>16;
n++;
The sequence of shifts and bitwise-ors guarantees a number that consists of all 1
s, which is one less than a power-of-2. Adding 1 to it gives a power-of-2.
The initial decrement by 1 is to make it work for values of n
that are already powers-of-2.
(Obviously, this code doesn't work if n
is originally 0
.)
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