Compute fast log base 2 ceiling

前端 未结 14 673
栀梦
栀梦 2020-11-28 11:35

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 ac

14条回答
  •  醉酒成梦
    2020-11-28 12:35

    Finding the log base 2 of an integer (64-bit or any other bit) with integer output is equivalent to finding the most significant bit that is set. Why? Because log base 2 is how many times you can divide the number by 2 to reach 1.

    One way to find the MSB that's set is to simply bitshift to the right by 1 each time until you have 0. Another more efficient way is to do some kind of binary search via bitmasks.

    The ceil part is easily worked out by checking if any other bits are set other than the MSB.

提交回复
热议问题