How can I manually set the bit value of a float that equates to NaN?

后端 未结 3 1738
一整个雨季
一整个雨季 2021-01-13 16:48

I\'m trying to run some tests with conversions and castings of floats to other types and I want to set my float variable to different values of nan.

\"a bit-wise exa

3条回答
  •  伪装坚强ぢ
    2021-01-13 17:44

    There is a supported way to write the payload of a quiet NaN in C.

    The nan, nanf, and nanl functions (of the math.h header, section 7.12.11.2 of the 1999 C specification) accept strings as arguments. The strtof, strtod, and strtold functions (of the stdlib.h header, section 7.20.1.3) accept strings of the form "NAN(character sequence)". The fscanf and sscanf functions follow strtod. However, the character sequence is interpreted in an implementation-defined way. (Which means your compiler is supposed to provide you with documentation specifying the interpretation. Some compilers will not obey this requirement of the standard.)

    The fprintf function (stdio.h, section 7.19.6.1) may output a string of the form "NAN(character sequence)" with the floating-point formats (a, e, f, g), as may printf and sprintf. The standard permits the output of "NAN" with no character sequence, so this will not work with many compilers.

    Because the interpretations are implementation-defined, you should not expect them to be portable. They are typically intended for special purposes such as debugging.

提交回复
热议问题