微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 双倍到十六进制字符串和十六进制字符串加倍

要做的是将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.
请指教 :)

解决方法

我很惊讶地看到没有人提出标准解决方案,这是ISO C99标准中的%格式说明符.
#include <iostream>
#include <string>
#include <stdio.h>

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;

}

原文地址:https://www.jb51.cc/c/117151.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐