This article explores different ways to calculate the log2 of a number in Kotlin.

1. Using ln() function

The idea is to use the ln(n) function to compute the natural logarithm (base e) of the value n and use the logarithmic identity to calculate log2(n). The logarithmic identity is logba = log10(a)/log10(b), therefore, log2n = log10(n)/log10(2). Note the following special cases as per the Kotlin docs:

  1. ln(NaN) is NaN
  2. ln(n) is NaN when n < 0.0
  3. ln(+Inf) is +Inf
  4. ln(0.0) is -Inf

Here's the working example:

Download Code

Output:

3.3219280948873626

2. Using Integer.numberOfLeadingZeros() function

The Integer.numberOfLeadingZeros() function returns the number of 0-bits preceding the most significant set bit. Then the log2(n) for a number n can be derived using the formula: 31 - Integer.numberOfLeadingZeros(n).

Download Code

Output:

3

That's all about calculating the log2 of a number in Kotlin.