Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Print representation of double in hex

Tags:

c++

cout

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.

like image 867
nccc Avatar asked Oct 16 '13 08:10

nccc


2 Answers

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

like image 53
user1233963 Avatar answered Oct 18 '22 18:10

user1233963


You can use this

    #include <iomanip> //Include this file
    cout<<hex<<*reinterpret_cast<unsigned __int64 *>(&r);
like image 22
singh Avatar answered Oct 18 '22 17:10

singh