log2() function in C++ with Examples Last Updated : 12 Jul, 2025 Comments Improve Suggest changes 7 Likes Like Report The function log2() of cmath header file in C++ is used to find the logarithmic value with base 2 of the passed argument. Syntax: log2(x) Parameters: This function takes a value x, in the range [0, ∞] whose log value is to be found. Return Type: It returns the logarithmic value, as double, float or long double type, based on the following conditions: If x > 1: It returns the positive logarithmic value of x. If x is equals to 1: It returns 0. If 0 < x < 1: It returns the negative logarithmic value of x. If x is equals to 0: It returns the negative infinity(-∞). If x < 0: It returns NaN(Not a Number). Below examples demonstrate the use of log2() method: Example 1: CPP // C++ program to illustrate log2() function #include <bits/stdc++.h> using namespace std; // Driver Code int main() { long b = 16; float c = 2.5; double d = 10.35; long double e = 25.5; // Logarithmic value of long datatype cout << log2(b) << "\n"; // Logarithmic value of float datatype cout << log2(c) << "\n"; // Logarithmic value of double datatype cout << log2(d) << "\n"; // Logarithmic value of long double datatype cout << log2(e) << "\n"; return 0; } Output: 4 1.32193 3.37156 4.67243 Example 2: CPP // C++ program to illustrate log2() function #include <bits/stdc++.h> using namespace std; // Driver Code int main() { // To show extreme cases int a = 0; int b = -16; // Logarithmic value of 0 cout << log2(a) << "\n"; // Logarithmic value of negative value cout << log2(b) << "\n"; return 0; } Output: -inf nan Reference: https://cplusplus.com/reference/cmath/log2/ Comment A akash_garg Follow 7 Improve A akash_garg Follow 7 Improve Article Tags : C++ CPP-Functions cpp-math Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like