This post will discuss how to calculate log2(x) for a number x in Java.

1. Using Math.log() method

The logarithmic identity logba = log10(a)/log10(b) is commonly used to derive log2 for a number x. i.e. log2x = log10(x)/log10(2).

The idea is to use the Math.log() method to find the natural logarithm of a number and then use above logarithmic identity to derive log2(x). Note that for negative numbers, the Math.log() method returns NaN and for zero value, it returns negative infinity.

Download  Run Code

2. Using Guava Library

Guava provides the LongMath.log2() method that returns the base-2 logarithm of a number, rounded according to the specified rounding mode.

Its usage is demonstrated below. Note that for non-positive numbers, LongMath.log2() throws java.lang.IllegalArgumentException.

Download Code

3. Using Integer.numberOfLeadingZeros() method

The idea here is to use the Integer.numberOfLeadingZeros() method to get the count of zero bits preceding the most significant set bit in the binary representation of a number. Then you can get the log2(x) for a number x using the formula: 31 - Integer.numberOfLeadingZeros(x).

This is demonstrated below. Note that for non-positive numbers, the code explicitly throws java.lang.IllegalArgumentException exception.

Download  Run Code

That’s all about calculating log2(x) for a number x in Java.