C++: Mantissa and Exponent of Floating Point Number

The little-known frexp function from the C/C++ standard library can be used to extract the mantissa and exponent of a floating point number (float, double or long double):

#include <cmath>

const double d = 0.123;
int exponent;
const double mantissa = frexp( d, &exponent );

// Double:   0.123
// Mantissa: 0.984
// Exponent: -3

A few notes:

  • frexp assumes that a floating point number is represented as mantissa * 2 ^ exponent. This is a simple and convenient representation to work with. But, do keep in mind that this is not how the floating point number is actually stored.
  • For a positive floating point number, the mantissa returned by frexp always lies in the range [0.5, 1.0). This range is enough since a mantissa in the range (0.0, 0.5) can be converted to a value in [0.5, 1.0) by multiplying it by a suitable 2 ^ exponent. Note that the exponent can be negative or positive. The exception to this mantissa value is the floating point number 0.0, which is displayed as it is.
  • The mantissa and exponent returned by frexp are in no way related to the actual mantissa and exponent values stored in the floating point number format. For example, the IEEE-754 format uses a sign bit and modifies the exponent value using an exponent bias.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.