Question

I just wonder if there exists better (i.e. faster?) way to get the next power of 2 for a given number than the following one (maybe some better sort of "bit-twiddling" hack is possible?) ...

static size_t
npow2(size_t n)
{
        n--;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        return n + 1;
}

Thanks for your ideas.

Was it helpful?

Solution

According to Sean Eron Anderson's collection of Bit Twiddling Hacks, that's probably the fastest way.

The alternatives are an IEEE float casting hack, which involves fewer C operations but ends up slower, and directly using the x86 BSR (bit scan reverse) machine instruction, but in Anderson's testing that didn't end up significantly faster than the above OR-ing trick.

Licensed under: CC-BY-SA with attribution
scroll top