What does this bit-manipulating function do?

http://stackoverflow.com/questions/8637142/what-does-this-bit-manipulating-function-do

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;
}
shareimprove this question
 
3  
It works pretty fast. –  Sergio Tulentsev Dec 26 '11 at 15:46
    
i know it works well, but i want to know which algorithm it use. –  guoxx Dec 26 '11 at 15:51
2  
Have a look here. –  Howard Dec 26 '11 at 15:51

2 Answers

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)

shareimprove this answer
 
    
The pre-decrement ensures inputs of zero and powers of two are mapped onto themselves. –  njuffa Dec 26 '11 at 17:41
 

This function rounds x up to the next highest power of 2. It's exactly the code in here

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
shareimprove this answer
 

posted on 2015-03-16 14:27  沉淀2014  阅读(149)  评论(0编辑  收藏  举报

导航