2
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;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
guoxx
  • 348
  • 1
  • 9
  • i know it works well, but i want to know which algorithm it use. – guoxx Dec 26 '11 at 15:51
  • 3
    Have 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 Answers1

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