转换为十六进制 - 代码审查 [英] Converting double to hexadecimal - Code review
问题描述
我有以下代码,它接受一个double值并将其转换为十六进制表示,反之亦然。我想知道是否有任何潜在的问题 - 是否我忽略了某些东西。
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;
}
它似乎工作得很好。但是我有人告诉我, char convert [bufferSize * 2]; 应该是
char convert [bufferSize * 2 + 1];
It seems to work fine. But I have been told by someone that char converted[bufferSize * 2];
should be char converted[bufferSize * 2 + 1];
是这样的吗?
推荐答案
,转换的大小
应为 bufferSize * 2 + 1
。您需要在字符串结尾处留空零字符或空字符。
Yes, the size of converted
should be bufferSize * 2 + 1
. You need room for a zero or null character at the end of the string.
sprintf
正在插入空字符在字符串的结尾,但你没有为它腾出空间;这意味着它会破坏缓冲区之后的内存中的某些值。很难预测这可能有什么副作用;它可能会弄乱一些其他变量的值,它可能会崩溃你的程序,或者它可能只是看起来工作正常。
sprintf
is 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.
这篇关于转换为十六进制 - 代码审查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!