In C++, std::frexp(x, &e)breaks a number into two parts: a fraction and a power of two. Every double can be written as m * 2e, where m is between 0.5 and 1. For 8 that is 0.5 * 24.
The function returns the fraction m and stores the exponent e in the int that you pass by address. The opposite function is std::ldexp(), which puts the parts back together. The sign of x goes to the fraction.
std::frexp() 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::frexp. Start with these lines.
C++
int e;
double m = std::frexp(8.0, &e); // m = 0.5, e = 4
double n = std::frexp(10.0, &e); // n = 0.625, e = 4
Call
What it does
std::frexp(8.0, &e)
Returns 0.5 and stores 4. 0.5 * 24 = 8.
std::frexp(10.0, &e)
Returns 0.625 and stores 4. 0.625 * 16 = 10.
std::frexp(0.1, &e)
Returns 0.8 and stores -3. 0.8 * 2-3 = 0.1.
The second argument is a pointer to an int, so write &e. Rebuild the number with std::ldexp(m, e).
The returned fraction is not needed here, so the call ignores it and only keeps the exponent in e.
255 is 0.996 * 28, so it needs 8 bits. 256 is exactly 0.5 * 29, so it needs 9.
1000 is 0.977 * 210, so it needs 10 bits. This works without a log, and it never has rounding trouble at powers of two.
Frequently Asked Questions
std::frexp(x, &e) splits x into a fraction m and a power of two, so that x = m * 2^e. The fraction m is between 0.5 and 1 (or between -1 and -0.5), and e is stored as an int.
The fraction m, with 0.5 <= |m| < 1. The exponent e is stored through the pointer. For 0, both are 0, and for infinity or NaN the result is unspecified.
The fraction is from 0.5 up to, but not including, 1 for positive numbers (and the same size with a minus sign for negatives). The exponent is chosen so that fraction * 2^exp equals x.
std::ldexp(m, e) multiplies m by 2 to the power e. So ldexp(frexp(x, &e), e) gives back x.
Include <cmath> and write std::frexp(). That always works and picks the C++ overloads. The global name ::frexp often works too, but the standard does not promise it, and it may only take a double.