double to hex string & hex string to double

后端 未结 9 1450
南方客
南方客 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.

提交回复
热议问题