What is a good bit-twiddling routine to convert a number in the range [2^N,2^(N-1)-1] to N?
Some examples:
- f(1) -> 0
- f([2-3]) -> 1
- f([4-7]) -> 2
- f([8-15]) -> 3
Here is one implementation:
uint f(uint num)
{
for (uint shifts = 0; num; shifts++)
num >>= 1;
return (shifts - 1);
}
Depending on how wide your data-type is, and how much memory you have available, a lookup-table is one possibility. It’s almost certainly the fastest approach.
For other approaches, see http://www-graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious, and the subsequent sections.