Search code examples
c++nan

How to print payload of a NaN?


We have special functions like std::nanl to make a NaN with a payload. Currently here's what I have to do to print it back:

#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdint>

int main()
{
    const auto x=std::nanl("1311768467463790325");
    std::uint64_t y;
    std::memcpy(&y,&x,sizeof y);
    std::cout << (y&~(3ull<<62)) << "\n";
}

This relies on the particular representation of long double, namely on it being 80-bit type of x87 FPU. Is there any standard way to achieve this without relying on such detail of implementation?


Solution

  • C++ imports nan* functions from ISO C. ISO C states in 7.22.1.3:

    the meaning of the n-char sequence is implementation-defined

    with a comment

    An implementation may use the n-char sequence to determine extra information to be represented in the NaN’s significand.

    There is no method to get the stored information.