首页 > 其他 > 详细

What does this bit-manipulating function do?

时间:2015-03-16 15:55:46      阅读:258      评论:0      收藏:0      [点我收藏+]

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
 

What does this bit-manipulating function do?

原文:http://www.cnblogs.com/xuejinhui/p/4341764.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!