将十六进制转换为双倍到十六进制

Convert Hex to Double to Hex?

本文关键字:十六进制 转换      更新时间:2023-10-16

在我的项目中,我有一个带有十六进制值的QString(大端序)

QString hex_in("413DF3EBA463B0");

如何将hex_in转换为四舍五入的双精度?IEEE 754 (https://en.wikipedia.org/wiki/Double_precision_floating-point_format)

34.5

用户将编辑双精度,然后我的程序需要将其转换回十六进制。

感谢您抽出宝贵时间:)

实际上

只有一种方法可以做到这一点,那就是将字符串转换为整数,将其放入设置整数成员并读出double成员的union中。

对于字符串转换,您可以使用例如这些函数之一。


示例代码:

double hexstr2double(const std::string& hexstr)
{
    union
    {
        long long i;
        double    d;
    } value;
    value.i = std::stoll(hexstr, nullptr, 16);
    return value.d;
}
// ...
std::cout << "413DF3EBA463B0 = " << hexstr2double("413DF3EBA463B0") << 'n';

上面代码的输出将是

413DF3EBA463B0 = 1.91824e-307
    double HexToDouble(AnsiString str)
{
  double hx ;
  int nn,r;
  char * ch = str.c_str();
  char * p,pp;
  for (int i = 1; i <= str.Length(); i++)
  {
    r = str.Length() - i;
    pp =   ch[r];
    nn = strtoul(&pp, &p, 16 );
    hx = hx + nn * pow(16 , i-1);
   }
  return hx;
}

我的大十六进制数字函数

结果

72850ccbb88c6226afed9d8d971c8938        -->     1.5222282653101E+38     
000015d85a903c72b6bebdd18fb26811        -->     4.4307191280143E+32