Search code examples
c++cgccassemblyieee-754

How to tell if a float is SNAN or QNAN


I am trying to figure out how to print out if a floating point number is QNAN or SNAN. I have already separated out the bits into the signBit exponentBit and the FractBits.

unsigned int sign = (i & 0x80000000) >> 31;
unsigned int exponent = (i & 0x7f800000) >> 23;
unsigned int fraction = (i & 0x007FFFFF);
printf("signBit %d, expBits %d, fractBits 0x%08X\n",sign, exponent, fraction);

Solution

  • GNU provides a facility which was recently standardized:

    Macro: int issignaling (float-type x)

    Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.

    This macro returns a nonzero value if x is a signaling NaN (sNaN). It is based on draft TS 18661 and currently enabled as a GNU extension.

    The final draft TS mentions that you might need to opt-in with a macro to get it:

    #define __STDC_WANT_IEC_60559_BFP_EXT__
    #include <math.h> 
    int issignaling(real-floating x);