C Programming/math.h/ldexp

In computing, ldexp is a function that multiplies a double precision floating point value by a specified integral power of two, returning the result if it is a valid floating point value for the representation used for double precision floating point values in the execution environment.

Location
It is one of the C programming language's math library routines and is declared in the header file math.h.

Definition
The function ldexp is defined in the C programming language standard, ISO/IEC 9899 as follows: 7.12.6.6 The ldexp functions Synopsis

""

Description

The ldexp functions multiply a floating-point number by an integral power of 2. A range error may occur.

Returns

The  functions return  *2exp

The Open Group Single Unix Specification expands on the interface definition for ldexp in a Unixtm hosted environment.


 * The Description section has the following additional information:
 * An application wishing to check for error situations should set errno to zero and call feclearexcept(FE_ALL_EXCEPT) before calling these functions. On return, if errno is non-zero or fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW) is non-zero, an error has occurred.


 * The "Returns" section is expanded with the following clauses:
 * If these functions would cause overflow, a range error must occur and,  , and   must return ± , ± , and ±  (according to the sign of  ), respectively.
 * If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value must be returned.
 * If x is NaN, a NaN must be returned.
 * If x is ±0 or ±Inf,  must be returned.
 * If exp is 0, x must be returned.
 * If the correct value would cause underflow, and is representable, a range error may occur and the correct value must be returned.


 * It also adds an "Errors section", as follows:
 * These functions must fail if:
 * Range Error
 * The result overflows.
 * If the integer expression (math_errhandling & MATH_ERRNO) is non-zero, then errno must be set to [ERANGE]. If the integer expression (math_errhandling & MATH_ERREXCEPT) is non-zero, then the overflow floating-point exception must be raised.

Implementation
For binary exponent based floating point representations such as IEEE 754, ldexp can be implemented by simply extracting the exponent from the value of  and adding   to it and if the result is within the valid exponent values for the representation, replacing  's exponent with the result. If the calculated exponent value is too high the function returns +∞ or -∞ (depending on the sign of ), and if the value is too low, the function returns 0.0.