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.
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:
nan
function from C and leaves it to C to specify what it does.nan("n-char-sequence")
is equivalent to strtod("NAN(n-char-sequence)", (char**)NULL)
."Hello"
is an n-char-sequence.strtod
with “NAN” with an *n-char-sequence, the meaning of the n-char-sequence is implementation-defined.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:
NaN
is converted in one of the styles [-]nan or [-]nan(n-char-sequence) — which style, and the meaning of any n-char-sequence, is implementation-defined.”