In C++, std::exp2(x) calculates 2 to the power of x. It is the quick way to get powers of two such as 8, 1024, or 0.5. Powers of two are everywhere in computing: bits, memory sizes, and binary trees.
It is the opposite of std::log2(), and it is more exact than std::pow(2.0, x). The result is a decimal type, so std::exp2(10) gives the double1024. It was added in C++11.
std::exp2() is declared in <cmath> and is part of the group Exponential and logarithm. Exponentials and logarithms undo each other. A logarithm of zero is -inf, and a logarithm of a negative number is NaN.
Syntax
Include <cmath> and call std::exp2. Start with these lines.
C++
double a = std::exp2(3.0); // double version
float b = std::exp2(3.0f); // float version
Call
What it does
std::exp2(3.0)
Passes a double and returns a double. Here the result is 8.
std::exp2(3.0f)
Passes a float, so the float overload runs and returns a float.
std::exp2(10)
An integer is converted to double. Returns 1024 as a double.
Write std::exp2 so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float exp2(float x);
double exp2(double x);
long double exp2(long double x);
double exp2(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. The exponent. Whole or fractional, positive or negative. An integer is converted to double.
Return Value
Return Value
Description
2x
Two raised to the power x, always greater than zero.
inf
The result is too big. For a double this happens for x of about 1024 or more.
0
The result is too small to store, such as exp2(-1100).
C++ Examples
Example 1 — Powers of Two
Print 2 to a few powers, including a fraction and a negative power.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {0.0, 3.0, 10.0, -1.0, 0.5};
for (double v : values) {
std::cout << "exp2(" << v << ") = " << std::exp2(v) << '\n';
}
return 0;
}
years / period counts how many doubling periods have passed. After 7 years that is 1.
exp2(1) is 2, so the money is 2000. After 14 and 21 years it is 4000 and 8000.
The exponent can be a fraction. At 3.5 years the exponent is 0.5, and exp2(0.5) is 1.41421, giving 1414.21.
Frequently Asked Questions
std::exp2(x) returns 2 raised to the power x. For example exp2(3.0) is 8 and exp2(10.0) is 1024.
Two to the power x as float, double, or long double. A negative x gives a fraction, and a very large x gives inf.
It is usually faster and more exact, and its name says what it does. Use exp2(x) when the base is always 2.
Use a shift: 1 << n gives 2 to the power n as an int. Keep n smaller than the number of bits in the type. Use exp2() when the exponent can be a fraction or negative.
Include <cmath> and write std::exp2(). That always works and picks the C++ overloads. The global name ::exp2 often works too, but the standard does not promise it, and it may only take a double.