C++: Print representation of double in hex
Asked Answered
S

3

6

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.

Sheerlegs answered 16/10, 2013 at 8:50 Comment(1)
https://mcmap.net/q/17201/-c-cout-hex-valuesMatroclinous
H
6

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

Hf answered 16/10, 2013 at 9:0 Comment(9)
Damn, exactly what I needed but g++ does not support it yet.Sheerlegs
Note that this doesn't do the same thing as your printf thing (which is also illegal, anyway).Grapeshot
Wasn't gcc supposed to be fully C++11 compliant?Hf
Not yet according to this gcc.gnu.org/onlinedocs/libstdc++/manual/status.htmlSheerlegs
@Grapeshot Why is my printf illegal?Sheerlegs
It breakes strict aliasing rules.Grapeshot
It's funny how gcc/clang/icc don't have hexfloat but MSVC doesHf
The big surprise from MS! :PSheerlegs
@Sheerlegs memcpy from double to uint64_t or ORing bytes together manualy.Grapeshot
C
3

You can use this

    #include <iomanip> //Include this file
    cout<<hex<<*reinterpret_cast<unsigned __int64 *>(&r);
Critchfield answered 16/10, 2013 at 9:7 Comment(0)
S
-2

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

std::cout << std::hex << num
Spatula answered 16/10, 2013 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.