1

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 :)

mrg95
  • 2,371
  • 11
  • 46
  • 89

2 Answers2

5

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
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I'm not converting a string to a number, I want what the string represents, hex, to convert to a number. Unless I misunderstood your answer? – mrg95 Sep 21 '13 at 22:47
  • @mc360pro But there is no way of knowing what number a string may represent, without converting the string *to* that number. – Some programmer dude Sep 21 '13 at 22:48
  • That is what I am trying to do. Convert this hex value into a number. Wouldn't converting JUST the string to a double convert the ascii characters or something and not what the actual hex values mean? – mrg95 Sep 21 '13 at 22:51
  • @mc360pro Instead of parsing each character, use the functionality already in the language and standard library. I've updated my answer with some very simple code. – Some programmer dude Sep 21 '13 at 22:59
  • Thanks for this :) However, is there anyway to get this as big endian? – mrg95 Sep 21 '13 at 23:00
  • 1
    @mc360pro Byte-swap the integer number. There are plenty of example on how to do it all over the Internet. – Some programmer dude Sep 21 '13 at 23:03
  • Thanks. I will mess with this and get back to you with an answer :) – mrg95 Sep 21 '13 at 23:03
  • 1
    @mc360pro [`htonll`](http://stackoverflow.com/questions/16375340/c-htonll-and-back) will come in handy. – IInspectable Sep 21 '13 at 23:06
  • How can I go from double back to hex with this method? – mrg95 Mar 26 '14 at 17:20
0
    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
Nike
  • 1