我要做的是将double转换为十六进制字符串然后再转换为double.
以下代码执行转换为双十六进制字符串.
char * double2HexString(double a) { char *buf = new char[17]; // double is 8-byte long, so we have 2*8 + terminating \0 char *d2c; d2c = (char *) &a; char *n = buf; int i; for(i = 0; i < 8; i++) { sprintf(n, "%02X", *d2c++); n += 2; } *(n) = '\0'; }
这似乎工作,但是,我不知道如何将结果字符串转换回double.请指教 :)
我很惊讶地看到没有人提出标准解决方案,这是%a
ISO C99标准中的格式说明符.
#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; }