How to generate NaN, -Infinity and +Infinity in ANSI C?

后端 未结 4 1846
南方客
南方客 2020-12-05 03:53

I use ANSI C89 (not C++), and I want to generate NaN, -Infinity and +Infinity.

Is there any standard way (eg. standard macro)?

4条回答
  •  遥遥无期
    2020-12-05 04:47

    There is an actual way to create infinity and negative infinity. Based on the IEEE 754 standard, which C89 follows, infinity is defined as a floating point number containing all zeroes in the mantissa (first twenty-three bits), and all ones in the exponent (next eight bits). nan is defined as any number with all ones in the exponent, and anything but all zeroes in the mantissa (because that's infinity). The difficult part is generating this number, but this can be accomplished with the following code:

    unsigned int p = 0x7F800000; // 0xFF << 23
    unsigned int n = 0xFF800000; // 0xFF8 << 20
    unsigned int pnan = 0x7F800001; // or anything above this up to 0x7FFFFFFF
    unsigned int nnan = 0xFF800001; // or anything above this up to 0xFFFFFFFF
    
    float positiveInfinity = *(float *)&p;
    float negativeInfinity = *(float *)&n;
    float positiveNaN = *(float *)&pnan;
    float negativeNaN = *(float *)&nnan;
    

    However, simply casting an unsigned to a float would result in the compiler creating a float of the same value. So, what we have to do is force the compiler to read the memory as a float, which gives us the desired result.

提交回复
热议问题