Although sstream is a fine answer... there are concerns and here about the use of streams in multithreaded programs.
similar solution with snprintf:
#include <iostream>
#include <cstdio>
double hexstr2double(const std::string& hexstr)
{
union
{
long long i;
double d;
} value;
value.i = std::stoll(hexstr, nullptr, 16);
return value.d;
}
std::string double2hexstr(double x) {
union
{
long long i;
double d;
} value;
value.d = x;
char buf[17];
snprintf (buf,sizeof(buf),"%016llx",value.i);
buf[16]=0; //make sure it is null terminated.
return std::string(buf);
}
int main(int argc,char **argv) {
double a=3.141592;
std::string x=double2hexstr(a);
double b=hexstr2double(x);
std::cout << a << std::endl;
std::cout << x << std::endl;
std::cout << b << std::endl;
return 0;
}
Edit (alternative version using std::ostringstream)
#include <iostream>
#include <sstream>
#include <iomanip>
double hexstr2double(const std::string& hexstr)
{
union
{
long long i;
double d;
} value;
value.i = std::stoll(hexstr, nullptr, 16);
return value.d;
}
std::string double2hexstr(double x) {
union
{
long long i;
double d;
} value;
value.d = x;
std::ostringstream buf;
buf << std::hex << std::setfill('0') << std::setw(16) << value.i;
return buf.str();
}
int main(int argc,char **argv) {
double a=3.141592;
std::string x=double2hexstr(a);
double b=hexstr2double(x);
std::cout << a << std::endl;
std::cout << x << std::endl;
std::cout << b << std::endl;
return 0;
}
Note... I'm not saying that std::ostringstream does not work. It has certainly better properties regarding memory safety (as snprintf has better properties over sprintf)... However be aware that (at least in some implementations of STL) in a multithreaded program might lead to excesive locking.