This post will discuss how to compute log base 2 of an integer in C#.

1. Using Math.Log() method

The Math.Log() method is commonly used to find the natural (base e) logarithm of a number. To get the logarithm of a number in some other base, you can use its 2-arg overload, and pass the base in the second parameter.

The following example illustrates the usage of the Math.Log(Double, Double) method by calculating the base-2 logarithm of a number 10.

Download  Run Code

 
To get the natural logarithm in base e, you can use the single argument Math.Log() method as follows:

Download  Run Code

2. Using BitOperations.Log2() method

If you need to obtain an integral part of the logarithm for a value in base 2, consider using the BitOperations.Log2() method. The following example demonstrates the usage of this simple and straightforward method. Note that BitOperations.Log2() method is included in the System.Numerics namespace.

Download  Run Code

That’s all about computing log base 2 of a value in C#.