double to hex string & hex string to double

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

    char *doubleToRawString(double x) {
        const size_t bytesInDouble = 8;
    
        union {
            double value;
            unsigned char bytes[bytesInDouble];
        } u;
    
        u.value = x;
    
        char *buffer = new char[bytesInDouble * 2 + 1];
        unsigned char *input = u.bytes;
        char *output = buffer;
    
        for(int i = 0; i < bytesInDouble; ++i) {
            sprintf(output, "%02hhX", *input);
    
            ++input;
            output += 2;
        }
    
        return buffer;
    }
    
    double rawStringToDouble(const char *input) {
        const size_t bytesInDouble = 8;
    
        union {
            double value;
            unsigned char bytes[bytesInDouble];
        } u;
    
        unsigned char *output = u.bytes;
    
        for(int i = 0; i < bytesInDouble; ++i) {
            sscanf(input, "%02hhX", output);
    
            input += 2;
            ++output;
        }
    
        return u.value;
    }
    

    This uses the non-standard hh modifier. If you don't want to use that, use:

    unsigned int tmp = *input;
    sprintf(output, "%02X", tmp);
    
    unsigned int tmp;
    sscanf(input, "%02X", &tmp);
    *output = tmp;
    

提交回复
热议问题