Solved
64-bit power of 2 calculation
Posted on 2007-11-25
I found online a nice algorithm for calculating the next highest power of 2. However, the algorithm takes a 32-bit integer. It seems to work just as well on 64-bit integers, but I'm not sure if it's guaranteed to always work. Will the following algorithm always return a 64-bit integer that is the next greatest power of 2?
uint64_t nextp2(uint64_t n)
{
--n;
n |= n >> 16;
n |= n >> 8;
n |= n >> 4;
n |= n >> 2;
n |= n >> 1;
++n;
return n;
}