c++floating-pointnanieee-754

When creating a nan which contains a char-sequence, how do I get the char-sequence back?


When doing

const double d = std::nan ("Hello");

you get a NAN containing the string "Hello". How can one back out this string from the variable d? Is there simply no standard conforming way? This feature seems to make little sense without being able to get the string back.


Solution

  • The C++ standard says an implementation may display the data encoded in a NaN when it is formatting it for fprintf, its relatives such as printf, and by C++ features that inherit from fprintf, such as output stream formatters. This is the only explicit provision in the C++ standard for getting information about the data in a NaN. (I am including statements in the C standard, which the C++ standard incorporates by reference.) About this, the standard says that an implementation may include the encoded data when it is formatting a NaN, but it is in an implementation-defined way, and an implementation may omit this.

    You can, of course, examine the data encoded in a NaN by examining the bytes that represent it. However, how the characters passed to the nan function are processed is implementation-defined. An implementation may choose to do nothing with them, it may include them literally in the bytes of the NaN (if they fit), or it may encode or interpret them, such as expecting a hexadecimal numeral in the string, which will be encoded into the bits of the NaN. The IEEE-754 basic 64-bit binary floating-point format commonly used for double has 51 bits available for the payload of a quiet NaN, which is enough to fix six eight-bit characters, so the string “Hello” could be encoded in a NaN.

    Here is a breakdown of what the standard says about the nan function:

    So, an implementation may encode the bytes you give it in the nan argument.

    What the C standard (and C++ by inheritance) says about formatting a NaN is: