0

I wish to count the number of places to the most significant bit in an unsigned integer.

For example

unsigned int i = b0000 1010 0110; // not proper C, b = binary representation
                       ^ MSB: number of places is 8

This is equivalent to counting the number of >>= operations required to obtain 0.

This is useful in algorithms which allocate storage on a 'power-of-2' basis. ie; if one requests 6 elements, 8 are allocated, if one requests 8 elements, 8 are allocated, if one requests 9 elements, 16 are allocated.

(Note: To obtain that allocation scheme, one must decrement by 1 first.)

Is there a faster way to do this operation with bit-hacks? My "simple" method just counts the number of shift-left operations required to obtain 0. (ie; my algorithm has a counter c, which is incremented in a loop while >>= is called repeatedly.)

The actual code I use is the following.

size_t nextpow2(size_t size)
{
    if(size == 0)
        return 0;
    -- size;

    size_t c = 0;
    for(; size != 0; size >>= 1, ++ c);

    return (1 << c);
}

I should add that I need to do this in a cross-platform manner. ie; the code must compile on GCC and Visual Studio 2013.

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

0 Answers0