直接上代码,以下是向上求解。
int pow2roundup(int x)
{
if (x < 0)
return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
以下是向下求解。
unsigned int dtPrevPow2(unsigned int v)
{
if (v % 2 != 0) {
v += 1;
}
v = v / 2;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
附上测试方法。
int main()
{
int a = dtPrevPow2(8000);
std::cout << a;
system("pause");
}