In C++, std::ldexp(x, e) calculates x times 2 to the power e. The name means "load exponent". ldexp(1.0, 10) is 1024, and a negative exponent divides: ldexp(3.0, -2) is 3 / 4 = 0.75.
The exponent e is an int. Multiplying by a power of two is exact, because it only changes the exponent of the number and leaves the digits alone. It is the opposite of std::frexp().
std::ldexp() is declared in <cmath> and is part of the group Remainder, scale, and compare. These functions split a number, scale it by a power of two, find its remainder, or pick between two numbers. They work directly on the binary form of a double.
Syntax
Include <cmath> and call std::ldexp. Start with these lines.
C++
double a = std::ldexp(1.0, 10); // 1024
double b = std::ldexp(0.5, 3); // 4
double c = std::ldexp(3.0, -2); // 0.75
Call
What it does
std::ldexp(1.0, 10)
1 * 210. Returns 1024.
std::ldexp(3.0, -2)
A negative exponent divides: 3 / 4. Returns 0.75.
std::ldexp(1.5f, 4)
The float overload. Returns 24.0f.
The exponent must be an int, not a double. For a decimal exponent, use std::exp2() or std::pow().
Library declarations
C++
float ldexp(float x, int exp);
double ldexp(double x, int exp);
long double ldexp(long double x, int exp);
double ldexp(Integer x, int exp); // for integer types
Parameters
Parameter
Description
x
Required. The number to scale. It can be float, double, long double, or an integer type.
exp
Required. The power of two, as an int. It can be negative.
Return Value
Return Value
Description
x * 2exp
The scaled number, in the type of x.
inf
The result is too big for the type (an overflow).
0
The result is too small to store (an underflow), or x is 0.
C++ Examples
Example 1 — Scale Several Numbers by Powers of Two
Print ldexp() for different numbers and exponents, including a negative one.
21023 is the biggest power of two that a double can hold. It prints as 8.98847e+307.
One more step, 21024, is too big and becomes inf. The program does not crash.
2-1075 is smaller than the smallest tiny number a double can store, so it is rounded to 0.
Frequently Asked Questions
std::ldexp(x, e) returns x multiplied by 2 to the power e. For example, ldexp(1.0, 10) is 1024 and ldexp(3.0, -2) is 0.75.
The value x * 2^e as float, double, or long double. If the result is too big it is inf, and if it is too small it is 0 or a tiny number.
ldexp(x, e) multiplies x by 2^e and is exact, because it only changes the exponent. It takes an int exponent. pow(2.0, e) is a general power function that works with any decimal exponent.
It is std::frexp(). frexp(x, &e) splits x into a fraction and a power of two, and ldexp(m, e) puts them back together.
Include <cmath> and write std::ldexp(). That always works and picks the C++ overloads. The global name ::ldexp often works too, but the standard does not promise it, and it may only take a double.