Computing the Integer Binary Logarithm
janmr.com·9h·
Discuss: Hacker News
🔢Bitwise Algorithms
Preview
Report Post

The binary logarithm, or the logarithm to the base 2, of a number x>0x > 0 is the number y=log2xy = log_2 x such that 2y=x2^y = x. This article looks at how we can determine the integer part of the binary logarithm using integer arithmetic only. Naturally, the binary logarithm is especially easy to work with on (binary) computers and bitwise operations come in handy.

As we saw in a previous post, we have

k=⌊log⁡2n⌋⇔2k≤n<2k+1.k = \lfloor \log_2 n \rfloor \quad \Leftrightarrow \quad 2^k \leq n < 2^{k+1}.

This means that we seek an integer kk such that ⌊n/2k⌋≠0\lfloor n/2^k \rfloor \neq 0 and ⌊n/2k+1⌋=0\lfloor n/2^{k+1} \rfloor = 0. We see that kk is the position of the left-most bit or, equ…

Similar Posts

Loading similar posts...