nccc
nccc

Reputation: 1155

C++: Print representation of double in hex

Is there a simple way to manipulate std::cout so that it prints doubles in their hex representation? In other words, something equivalent to:

printf("%" PRIx64, *reinterpret_cast<uint64_t *>(&my_double));

To provide some context, I have a program which prints hundreds of floating-point results and I was wondering if there is that magical one-line hack that can print all of them in hex.

Upvotes: 6

Views: 12484

Answers (3)

singh
singh

Reputation: 439

You can use this

    #include <iomanip> //Include this file
    cout<<hex<<*reinterpret_cast<unsigned __int64 *>(&r);

Upvotes: 3

user1233963
user1233963

Reputation: 1490

Take a look at std::hexfloat if you can use C++11

Example:

double k = 3.14;
std::cout<< std::hexfloat << k << std::endl;

prints: 0x1.91eb85p+1

Upvotes: 6

Paul Evans
Paul Evans

Reputation: 27577

You can get std::cout to print in hex with:

std::cout << std::hex << num

Upvotes: -2

Related Questions