我希望下面的代码显示两条相等的行:
#include <stdio.h>
int main(void) {
//printf("%x %x %x\n", '\x7F', (unsigned char)'\x8A', (unsigned char)'\x8B');
printf("%x %x %x\n", '\x7F', '\x8A', '\x8B');
printf("%x %x %x\n", 0x7F, 0x8A, 0x8B);
return 0;
}
我的输出:
7f ffffff8a ffffff8b
7f 8a 8b
我知道这可能是溢出情况。但为什么是 ffffff
8a
(4 个字节)...?
最佳答案
'\x8A'
是,根据cppreference ,
a single-byte integer character constant, e.g.
'a'
or'\n'
or'\13'
.
特别有趣的是以下内容。
Such constant has type
int
and a value equal to the representation of c-char in the execution character set as a value of typechar
mapped toint
.
这意味着 '\x8A'
到无符号 int 的转换是实现定义的,因为 char
可以是有符号的,也可以是无符号的,具体取决于系统。如果 char
有符号,就像您的情况一样(并且很常见),那么 '\x8A'
的值(负数)作为32 位 int
为 0xFFFFFF8A
(也是负数)。但是,如果 char
是无符号的,那么它就会变成 0x0000008A
(这就是代码中的注释行按照您的预期工作的原因)。
printf 格式说明符 %x
用于 convert an unsigned integer into hexadecimal representation 。尽管 printf
需要一个 unsigned int
并且您给它一个 int
,并且即使标准规定将不正确的类型传递给 printf
是(通常)未定义的行为,它不适合您的情况。这是因为从 int
到 unsigned int
的转换是明确定义的,尽管相反的转换不是明确定义的。
关于c - 为什么大于 x7F 的十六进制编码字符在 printf 函数中显示不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334793/