Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
Toby Brull Avatar asked Aug 16 '18 07:08

Toby Brull


1 Answers

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++ 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:

  • C++ inherits the nan function from C and leaves it to C to specify what it does.
  • C says that nan("n-char-sequence") is equivalent to strtod("NAN(n-char-sequence)", (char**)NULL).
  • C says an n-char-sequence is a sequence of digit and nondigit characters. The digit characters are 0-9, and the nondigit characters are _, A-Z, and a-z. So the string "Hello" is an n-char-sequence.
  • C says, about 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:

  • “A double argument representing a 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.”
like image 123
Eric Postpischil Avatar answered Nov 18 '22 03:11

Eric Postpischil