使用 %d 说明符在 C 中打印无符号字符时的奇怪结果 [英] Weird result when using the %d specifier to print an unsigned char in C
问题描述
有点奇怪.我只是使用无符号字符类型和负值.我有以下代码.
It is little bit weird. I just play with the unsigned char type and negative values. I have the following code.
#include <stdio.h>
int main(int argc, char* agrv[]){
unsigned char c = -3;
printf("%d, %u, %d, %u\n", c, c, ~c, ~c);
}
输出是,
253, 253, -254, 4294967042
我无法弄清楚最后三个值.%d 和 %u 实际上是做什么的?
I can not figure out the last three values. What does %d and %u really do?
推荐答案
%d
格式打印出一个 int
和 %u
打印出一个 unsigned int
.所有对 unsigned char
值的算术都是通过首先将它们转换为 int
并对 int
值进行运算来完成的,所以 ~c
(等于 -1 - (int)c
)将返回一个负的 int
值.需要显式转换才能在打印出 unsigned char
结果之前获得它(并且对 printf
的调用无论如何都会将其转换回 int
).
The %d
format prints out an int
, and %u
prints out an unsigned int
. All arithmetic on unsigned char
values is done by first casting them to int
and doing the operations on int
values, and so ~c
(which is equal to -1 - (int)c
) will return a negative int
value. An explicit cast would be needed to get the unsigned char
result before printing it out (and the call to printf
would cast it back to int
anyway).
这篇关于使用 %d 说明符在 C 中打印无符号字符时的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!