gpt4 book ai didi

c - sscanf %u 不解释十六进制

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:12 24 4
gpt4 key购买 nike

我正在尝试使用 sscanf 的“%u”格式说明符将十六进制或十进制文本转换为无符号整数。结果不正确,对于值 0x01,sscanf 返回 0 (0)。

根据 C++ Reference , "%u"说明符的定义(突出显示是我的):
i, u Integer 任意数量的数字,前面可以有一个符号(+ 或 -)。默认采用十进制数字 (0-9),但 0 前缀引入八进制数字 (0-7)、和 0x 十六进制数字 (0-f)

根据 Harbison & Steele,第 3 版:
u 转换 执行无符号十进制转换。...读取的数字格式与 strtol 函数的输入预期相同,base 参数的值为 10;这是一个十进制数字序列,前面可选 - 或 +。

请注意,其中一个定义允许在字符串中指定“0x”。

我正在使用 IAR EW 编译器,编译设置为 C99 方言。

哪个定义对于 C99 是正确的?

我在以下程序中收到两个不同的结果。

这是一个测试程序:

#include <stdio.h>
int main(void)
{
const char text[] = "0x01 1";
unsigned int first_value = 0U;
unsigned int second_value = 0U;
signed int arguments_satisfied = 0;
arguments_satisfied = sscanf(text, "%u %u", &first_value, &second_value);
printf("Arguments scanned: %d, first: %d, second: %d\n",
arguments_satisfied, first_value, second_value);
return EXIT_SUCCESS;
}

最佳答案

根据当前的 C 标准,C11,7.21.6.2/12,只有 %i 从上下文推导基数,所有其他说明符固定基数:

i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.

o Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 8 for the base argument. The corresponding argument shall be a pointer to unsigned integer.

u Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer.

x Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.

关于c - sscanf %u 不解释十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969619/

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