What is the log2() function in C++?

Overview

The log2() function is used to return the logarithm to base-2 of the argument passed to it.

Syntax

double log2(double x);
float log2(float x);
long double log2(long double x);
double log2(T x); // For integral type

Parameter value

The log2() function takes only one parameter with a value between zero and infinity.

Return value

The log2() function returns the logarithm of a number in base-2.

When the argument passed to the function is less than zero, the function returns NaN (Not a Number).

The table below shows the return value of the log2() function for any given input:

Parameter (x) Return value
x < 0 NaN (Not a Number)
x > 0 Positive
x = 1 Zero
x = 0 negative infinity (-∞)

Example

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// creating a variable
int x = 1000, result;
// using the log2() function
result = log2(x);
cout << "log2(x) = " << result << endl;
x = -3.591;
result = log2(x);
cout << "log2(x) = " << result << endl;
return 0;
}

Explanation

  • Line 9: We create a variable, x.
  • Line 12: We implement the log2() function on the x variable and assign the output to another variable, result.
  • Line 13: We print the result variable.

We replicate the same code but with a different argument value in the rest of the code.

Free Resources