I need to print a IEEE 64-bit double
as hex string.
I understand I have to use std::hexfloat
in some way. But how to get the state of the stream right before that so it can be reset to the initial state?
Must the precision also be hacked if the goal is to print with the highest possible precision? Or is that already a feature of hexfloat?
The output must be in such a way that it can be used in a C/C++ source without any further ado, e.g. -0x123.abc42p+10
.
The language I am using is C++11. Not more, not less.
But how to get the state of the stream right before that so it can be reset to the initial state?
You can use the stream's flags()
function to retrieve and save the current settings, then later use the setf()
function to restore them, being sure to include std::ios_base::floatfield
in the "mask" (second argument).
Must the precision also be hacked if the goal is to print with the highest possible precision? Or is that already a feature of hexfloat?
Yes. From cppreference:
Hexadecimal floating-point formatting ignores the stream precision specification, as required by the specification of std::num_put::do_put.
Here's a short demonstration program that may help:
#include <iostream>
using std::cout; using std::endl;
int main()
{
double test = -0x123.abc42p+10;
cout << std::fixed; // Change from the default for demo
cout << test << endl; // Display in "Current" format
auto fSave = cout.flags(); // Save current flags
cout << std::hexfloat; // Change to HEX float
cout << test << endl; // ... and display
cout.setf(fSave, std::ios_base::floatfield); // Restore float field
cout << test << endl; // Restored to previous settings!
return 0;
}