Warm tip: This article is reproduced from stackoverflow.com, please click
c c++ linux floating-point ieee-754

How can the significand width in bits of float, double be determined: Is there a standard definition

发布于 2020-03-27 10:25:21

Is there a standard manner to determine the width of the significand of a double, in C or C++? I am aware that IEEE-754 format of a double stores the significand in 53 bits, but I would like to avoid using a “magic” number in my code.

On Linux, the file usr/include/ieee754.h exists, but it describes the format using bit fields in a structure, which I cannot determine the size of (at compile time).

A Linux-only solution is acceptable.

Questioner
Jamie
Viewed
100
Eric Postpischil 2019-07-03 23:06

Use FLT_MANT_DIG and DBL_MANT_DIG, defined in <float.h>:

#include <float.h>
#include <stdio.h>


#if FLT_RADIX != 2
    #error "Floating-point base is not two."
#endif


int main(void)
{
    printf("There are %d bits in the significand of a float.\n",
        FLT_MANT_DIG);
    printf("There are %d bits in the significand of a double.\n",
        DBL_MANT_DIG);
}