I have the following code that takes a double value and converts it to a hexadecimal representation, and vice versa. I would like to know whether there are any potential problems with it – whether I have overlooked something.
double hex_to_double2(string &hexString)
{
unsigned char byte_string[sizeof(double)];
int number;
int j = 0;
for(int i = 0; i < hexString.size() ; i += 2)
{
sscanf(&hexString[i], "%02x", &number);
byte_string[j] = (unsigned char)number;
++j;
}
double p = (double&)byte_string;
return p;
}
std::string double_to_hex_string(double d)
{
unsigned char *buffer = (unsigned char*)&d;
int bufferSize = sizeof(double);
char converted[bufferSize * 2];
int j = 0;
for(int i = 0 ; i < bufferSize ; ++i)
{
sprintf(&converted[j*2], "%02X", buffer[i]);
++j;
}
string hex_string(converted);
return hex_string;
}
It seems to work fine. But I have been told by someone that char converted[bufferSize * 2]; should be char converted[bufferSize * 2 + 1];
Is this the case?
Yes, the size of
convertedshould bebufferSize * 2 + 1. You need room for a zero or null character at the end of the string.sprintfis inserting a null character at the end of the string, but you didn’t make space for it; this means it’s destroying some value in memory that comes just after the buffer. It’s hard to predict what side effect this might have; it might mess up the value of some other variable, it might crash your program, or it might just appear to work fine.