C# Math.Log2() – Examples

In this tutorial, we will learn about the C# Math.Log2() method, and learn how to use this method to compute base 10 logarithm of a specified number, with the help of examples.

Log2(Double)

Math.Log2(d) returns the base 2 logarithm of a specified number d.

ADVERTISEMENT

Syntax

The syntax of Log2() method is

Math.Log2(Double d)

where

ParameterDescription
dThe double value, whose base 2 logarithm is to be found.

Return Value

The method returns value of type double.

Example 1 – Log2(d)

In this example, we will find the base 2 logarithm of the following numbers.

  • Positive Value
  • Negative Value
  • Positive Infinity
  • Negative Infinity
  • Zero

C# Program

using System;
 
class Example {
    static void Main(string[] args) {
        Double d, result;
 
        d = 8;
        result = Math.Log2(d);
        Console.WriteLine($"Log2({d}) = {result}");
 
        d = -7;
        result = Math.Log2(d);
        Console.WriteLine($"Log2({d}) = {result}");
 
        d = Double.PositiveInfinity;
        result = Math.Log2(d);
        Console.WriteLine($"Log2({d}) = {result}");
 
        d = Double.NegativeInfinity;
        result = Math.Log2(d);
        Console.WriteLine($"Log2({d}) = {result}");
 
        d = 0;
        result = Math.Log2(d);
        Console.WriteLine($"Log2({d}) = {result}");
    }
}

Output

Log2(8) = 3
Log2(-7) = NaN
Log2(∞) = ∞
Log2(-∞) = NaN
Log2(0) = -∞

Conclusion

In this C# Tutorial, we have learnt the syntax of C# Math.Log2() method, and also learnt how to use this method, with the help of C# example programs.