How does this code work to find the next maximum power of 2 for any given number

How does this code work for Find the next maximum power of 2 for any given number [> 1] for a 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++; 
+4
source share
2 answers

A sequence of shifts and bitwise eagles guarantees a number consisting of all 1 s, which is less than a unit of power. Adding 1 to it gives a power of 2.

The initial decrement of 1 is to make it work for n values ​​that are already parameters-2.

(Obviously, this code does not work if n initially 0 )

+7
source

Reducing will make the case 2 ^ n, to give the result 2 ^ n instead of 2 ^ (n + 1). This does not correspond to the increment at the end.

The part between decrement and increment actually tries to fill the entire bit, which is less significant than the most significant bit, which is 1. The most significant bit, which is 1, will gradually spread after each line and will fill less and less Important bits on the last line.

An increment is to get the result of the next highest degree 2.

+1
source

All Articles