Search code examples
c++clinuxfloating-pointieee-754

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


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.


Solution

  • 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);
    }