我正在尝试在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。
我错在哪里了?
strtol
会尝试从输入字符串的开头自行确定使用基数16、10还是8。 - Daniel Fischer