unsigned long ccNextPOT(unsigned long x){
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
return x + 1;
}
Asked
Active
Viewed 235 times
2
-
i know it works well, but i want to know which algorithm it use. – guoxx Dec 26 '11 at 15:51
-
3Have a look [here](http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2). – Howard Dec 26 '11 at 15:51
-
Possible duplicate of [Rounding up to next power of 2](https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2) – phuclv Jul 19 '18 at 03:18
1 Answers
3
The OR and SHIFT statements fills with ones all bits of x
to the right of most significant bit (up to 32 bits). Together with the pre-decrement and post-increment statements, this computes (as the function name suggets) the next power-of-two number, equal or greater than the given number (if x
is greater than 0 and less than 2^32)

leonbloy
- 73,180
- 20
- 142
- 190
-
The pre-decrement ensures inputs of zero and powers of two are mapped onto themselves. – njuffa Dec 26 '11 at 17:41