C++ Standard Library C++ STL Library

C++ <cmath> - log2() Function



The C++ <cmath> log2() function returns the base-2 (binary) logarithm of a given number.

Syntax

double log2 (double x);
float log2 (float x);
long double log2 (long double x);
double log2 (T x);                     

Parameters

x Specify the number.

Return Value

Returns the base-2 (binary) logarithm of a given number.
If the x is negative, domain error occurs.

Example:

In the example below, log2() function is used to calculate the base-2 (binary) logarithm of a given number.

#include <iostream>
#include <cmath>
using namespace std;
 
int main (){
  cout<<log2(2)<<"\n";
  cout<<log2(32)<<"\n";
  cout<<log2(50)<<"\n";
  return 0;
}

The output of the above code will be:

1
5
5.64386

❮ C++ <cmath> Library