unsigned int x; // calculate the next highest power of 2 of 32-bit x
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
Round up to the next highest power of 2 by float casting:
This operation is 3 times slower than above operation.
unsigned int const v; // Round this 32-bit value to the next highest power of 2
unsigned int r; // result here. (So v=3 -> r=4; v=8 -> r=8)
if (v > 1)
{
float f = (float)v;
unsigned int const t = 1U << ((*(unsigned int *)&f >> 23) - 0x7f);
r = t << (t < v);
}
else
{
r = 1;
}
No comments:
Post a Comment