Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this code work to Find the next highest power of 2 for any given number

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++;
like image 824
Green goblin Avatar asked Feb 21 '23 03:02

Green goblin


1 Answers

The sequence of shifts and bitwise-ors guarantees a number that consists of all 1s, 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.)

like image 74
Oliver Charlesworth Avatar answered Feb 23 '23 11:02

Oliver Charlesworth