double to hex string & hex string to double

后端 未结 9 1381
南方客
南方客 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:44

    Almost the same procedure should do

    void hex2double(const char* buf, double& a)
    {
       char tmpbuf[3]={0};
       char *d2c;
       unsigned int tmp;
       d2c = (char *) &a;
       char *n = buf;
       int i;
       for(i = 0; i < 8; i++)
       {
          tmpbuf[0]=*buf++;
          tmpbuf[1]=*buf++;
          sscanf(tmpbuf, "%X", &tmp);
          *d2c++=tmp;
       }
    }
    

    Quick & dirty.

    Note, however, that this is playing with fire. First, your hex strings are only usable on machines with the same double format, and the same endianness. Second, the conversion functions are short on strict aliasing rule.

    0 讨论(0)
  • 2021-01-02 21:44

    I am using the below function, to convert double to hexadecimal.

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

    passing 1.0 & 16.0 to this function, the return values observed are 000000000000FF37 & 0000000000003040 respectively. I think we should get 1 & 10.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题