您的位置:首页 > 其它

What does this bit-manipulating function do?

2015-03-16 14:27 369 查看
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;
}


bit-manipulation
shareimprove this question
edited Dec 26 '11 at 16:42



Ondrej Tucny
13.8k22450

asked Dec 26 '11 at 15:45



guoxx
1007

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

add a comment

2 Answers

activeoldestvotes

up vote2down vote

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

answered Dec 26 '11 at 16:54



leonbloy
30.5k66491

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

add a comment

up vote0down vote

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
edited Aug 1 '13 at 8:08

answered Jul 31 '13 at 13:45



Lưu Vĩnh Phúc
4,75831332

add a comment

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: