C++ log2()

The function is defined in <cmath> header file.

[Mathematics] log2x = log2(x) [In C++ Programming]

log2() prototype [As of C++ 11 standard]

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

The log2() function takes a single argument and returns a value of type double, float or long double.


log2() Parameters

The log2() function takes a single mandatory argument in the range [0, ∞].
If the value is less than zero, log2() returns NaN (Not a Number).


log2() Return value

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

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

Example 1: How log2() function works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double x = 13.056, result;

	result = log2(x);
	cout << "log2(x) = " << result << endl;

	x = -3.591;
	result = log2(x);
	cout << "log2(x) = " << result << endl;
	
	return 0;
}

When you run the program, the output will be:

log2(x) = 3.70664
log2(x) = nan

Example 2: log2() function with integral type

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double result;
	int x = 2201;

	result = log2(x);
	cout << "log2(" << x << ") = " << result << endl;

	return 0;
}

When you run the program, the output will be:

log2(2201) = 11.1039

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community