【发布时间】:2012-07-22 14:37:20
【问题描述】:
我正在尝试在 32 位机器上进行十六进制到整数的转换。这是我正在测试的代码,
int main(int argc,char **argv)
{
char *hexstring = "0xffff1234";
long int n;
fprintf(stdout, "Conversion results of string: %s\n", hexstring);
n = strtol(hexstring, (char**)0, 0); /* same as base = 16 */
fprintf(stdout, "strtol = %ld\n", n);
n = sscanf(hexstring, "%x", &n);
fprintf(stdout, "sscanf = %ld\n", n);
n = atol(hexstring);
fprintf(stdout, "atol = %ld\n", n);
fgetc(stdin);
return 0;
}
这是我得到的:
strtol = 2147483647 /* = 0x7fffffff -> overflow!! */
sscanf = 1 /* nevermind */
atol = 0 /* nevermind */
如您所见,使用 strtol 时出现溢出(我也使用 errno 检查过),尽管我希望不会发生任何情况,因为 0xffff1234 是一个有效的 32 位整数值。 我要么期望 4294906420 要么 -60876
我错过了什么?
【问题讨论】:
-
你确定将基数设置为 0 就是 16。我的意思是用 替换 strtol(hexstring, (char*)0, 0)* strtol(hexstring, (char*)0, 16)*
-
@A.G.将基数设置为 0 意味着
strtol会尝试从输入字符串的开头自行计算,是否使用基数 16、10 或 8。 -
对,我忘了!谢谢!
标签: c hex type-conversion integer-overflow strtol