double to hex string & hex string to double

后端 未结 9 1419
南方客
南方客 2021-01-02 20:51

What I\'m trying to do is to convert a double to hex string and then back to double.

The following code does conversion double-to-hex string.

char *          


        
9条回答
  •  攒了一身酷
    2021-01-02 21:49

    Using sprintf is slow, to be honest, but you can revert it with sscanf, doing almost exactly the same thing.

    Well, actually, you'd have to copy each two characters to a buffer string, to decode each individually. My first try, below is incorrect:

    double hexString2Double(char *buf)
    {
      char *buf2 = new char[3];
      double a;
      char* c2d;
      c2d = (char *) &a;
      int i;
    
      buf2[2] = '\0'
    
      for(i = 0; i < 16; i++)
      {
        buf2[0] = *buf++;
        buf2[1] = *buf++;
        sscanf(buf2, "%X", c2d++);
      }
    
      return a;
    }
    

    You see, %X is decoded as an int, not as a byte. It might even work, depending on low-ending/high-endian issues, but it's basically broken. So, let's try to get around that:

    double hexString2Double(char *buf)
    {
      char *buf2 = new char[3];
      double a;
      char* c2d;
      c2d = (char *) &a;
      int i;
      int decoder;
    
      buf2[2] = '\0'
    
      for(i = 0; i < 16; i++)
      {
        buf2[0] = *buf++;
        buf2[1] = *buf++;
        sscanf(buf2, "%X", &decoder);
        c2d++ = (char) decoder;
      }
    
      return a;
    }
    

    Barring syntax errors and such, I think this should work.

提交回复
热议问题