Convert Hex to Double to Hex?

南楼画角 提交于 2020-01-23 17:42:50

问题


In my project I have a QString with the hex value (Big Endian)

QString hex_in("413DF3EBA463B0");

How could I convert hex_in to a rounded double? IEEE 754 (https://en.wikipedia.org/wiki/Double_precision_floating-point_format)

34.5

The user will edit the double and then my program needs to convert it back to hex.

Thanks for your time :)


回答1:


There is really only one way to do it, and that is to convert the string to an integer, put it in a union where you set an integer member and read out a double member.

For the string conversion you can use e.g. one of these functions.


Example code:

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';

The output of the code above will be

413DF3EBA463B0 = 1.91824e-307



回答2:


    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;
}

my function for big hex digit

result

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


来源:https://stackoverflow.com/questions/18938429/convert-hex-to-double-to-hex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!