C++ frexp()

C++ frexp() breaks given (float) number to its binary significand and an integer exponent for 2.

If x is argument to frexp(), then we find binary significand and exponent for 2 as given by the following equation.

x = binary significand * 2^exponent

Syntax

The syntax of C++ frexp() is

frexp(x, exp)

where

ParameterDescription
xA double, float, long double, or any integral type value.
expThe exponent is stored at this address. The value stored in this address is an integer.

Returns

The return value depends on the type of value passed for parameter x.

The return value of frexp(x) is

  • double if x is double or integral type.
  • float if x is float.
  • long double if x is long double.

The synopsis of frexp() function is

double frexp(double x, int* exp);
float frexp(float x, int* exp);
long double frexp(long double x, int* exp);
double frexp(T x, int* exp); // for integral type argument values

frexp() is a function of cmath library. Include cmath library in the program, if using frexp() function.

Example

In this example, we read a value from user into variable x, and find the value of binary significand and exponent for 2, using frexp() function.

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x;
    cout << "Enter a number     : ";
    cin >> x;
    
    int exp;
    double result = frexp(x, &exp);
    cout << "Binary Significand : " << result << endl;
    cout << "Exponent           : " << exp << endl;
}

Output

Enter a number     : 8
Binary Significand : 0.5
Exponent           : 4
Program ended with exit code: 0
Enter a number     : 15
Binary Significand : 0.9375
Exponent           : 4
Program ended with exit code: 0
Enter a number     : -5
Binary Significand : -0.625
Exponent           : 3
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned the syntax of C++ frexp(), and how to use this function to find the binary significand and exponent for 2, with the help of examples.