What I\'m trying to do is to convert a double to hex string and then back to double.
The following code does conversion double-to-hex string.
char *
I am surprised to see nobody has come up with the standard solution, which is the %a format specifier in the ISO C99 Standard.
#include
#include
#include
std::string double2hexastr(double d) {
char buffer[25] = { 0 };
::snprintf(buffer, 25, "%A", d); // TODO Check for errors
return buffer;
}
double hexastr2double(const std::string& s) {
double d = 0.0;
::sscanf(s.c_str(), "%lA", &d); // TODO Check for errors
return d;
}
int main() {
std::cout << "0.1 in hexadecimal: " << double2hexastr(0.1) << std::endl;
std::cout << "Reading back 0X1.999999999999AP-4, it is ";
std::cout << hexastr2double("0X1.999999999999AP-4") << std::endl;
}