gpt4 book ai didi

将十六进制字符串转换为长

转载 作者:行者123 更新时间:2023-12-04 11:15:21 26 4
gpt4 key购买 nike

我正在尝试在 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

我错过了什么?

最佳答案

如果您不想要溢出效果,请不要使用函数的带符号变体。请改用 strtoul()

使用以下代码:

#include <stdio.h>
int main(int argc,char **argv) {
char *hexstring = "0xffff1234";
long sn;
unsigned long un;

fprintf(stdout, "Conversion results of string: %s\n", hexstring);

sn = strtoul(hexstring, (char**)0, 0);
fprintf(stdout, "strtoul signed = %ld\n", sn);

un = strtoul(hexstring, (char**)0, 0);
fprintf(stdout, "strtoul unsigned = %lu\n", un);

return 0;
}

我得到:

Conversion results of string: 0xffff1234
strtoul signed = -60876
strtoul unsigned = 4294906420

当调用 strtol() 及其同类函数时,您无法控制它,因为该行为那些函数中。该标准是这样说的:

The strtol, strtoll, strtoul, and strtoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno.

关于将十六进制字符串转换为长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11628124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com