Checking if a double (or float) is NaN in C++

后端 未结 21 1891
北恋
北恋 2020-11-22 05:10

Is there an isnan() function?

PS.: I\'m in MinGW (if that makes a difference).

I had this solved by using isnan() from , which doe

21条回答
  •  难免孤独
    2020-11-22 05:46

    inline bool IsNan(float f)
    {
        const uint32 u = *(uint32*)&f;
        return (u&0x7F800000) == 0x7F800000 && (u&0x7FFFFF);    // Both NaN and qNan.
    }
    
    inline bool IsNan(double d)
    {
        const uint64 u = *(uint64*)&d;
        return (u&0x7FF0000000000000ULL) == 0x7FF0000000000000ULL && (u&0xFFFFFFFFFFFFFULL);
    }
    

    This works if sizeof(int) is 4 and sizeof(long long) is 8.

    During run time it is only comparison, castings do not take any time. It just changes comparison flags configuration to check equality.

提交回复
热议问题