Compute log2 of an integer in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int i = 10; int b = 2; double result = Math.Log(i, b); Console.WriteLine(result); // 3.3219280948873626 } } |
To get the natural logarithm in base e, you can use the single argument Math.Log() method as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int i = 10; double result = Math.Log(i); Console.WriteLine(result); // 2.302585092994046 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Numerics; public class Example { public static void Main() { uint i = 10; int result = BitOperations.Log2(i); Console.WriteLine(result); // 3 } } |
That’s all about computing log base 2 of a value in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)