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 *
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;