What is a fast way to compute the (long int) ceiling(log_2(i))
, where the input and output are 64-bit integers? Solutions for signed or unsigned integers are acceptable. I suspect the best way will be a bit-twiddling method similar to those found here, but rather than attempt my own I would like to use something that is already well tested. A general solution will work for all positive values.
For instance, the values for 2,3,4,5,6,7,8 are 1,2,2,3,3,3,3
Edit: So far the best route seems to be to compute the integer/floor log base 2 (the position of the MSB) using any number of fast existing bithacks, and then to add one if the input is not a power of two. The fast bitwise check for powers of two is (n&(n-1))
.
Another method might be to try a binary search on exponents e
until 1<<e
is greater than or equal to the input.