有符号和无符号数据类型之间的区别?
main()
{
char i=255;
printf("\n%x\n",i);
}
输出:ffffffff
main()
{
u_char i=255;
printf("\n%x\n",i);
}
输出:ff
这里发生了什么?请用一些好的链接向我解释输出。我想这是一个非常基本的事情,我真的很困惑......
main()
{
char i=255;
printf("\n%x\n",i);
}
output:ffffffff
main()
{
u_char i=255;
printf("\n%x\n",i);
}
output:ff
What is happening here? Kindly explain the output to me with some good links. This is a very basic thing I guess and I am getting really confused...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(4)
半窗疏影2024-11-09 05:50:50
C 编译器必须扩展传递给 printf 的值(这称为“提升”),因为 printf 是一个可变参数函数(可以使用不同的参数调用它)。对于 char
类型的值,提升后的值为 int
类型。由于编译器的 char
类型似乎是有符号的,因此提升的值是符号扩展的。在二进制中:
char i = 255 // or: 11111111 in binary
int promoted_i = -1 // or: 11....11111 (usually, 32 or 64 ones)
在无符号的情况下,不会发生符号扩展:
char u = 255 // or: 11111111 in binary, same as above but with different interpretation
unsigned int pu = i // or: 00....0011111111 (8 ones, preceded by the appropriate number of zeroes)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您在这里看到的情况是由两件事引起的:
255
不适合char
的范围(请注意,是否char
是实现定义的> 相当于signed char
或unsigned char
,但显然在您的平台上它是signed char
)。结果行为是实现定义的,但通常它会回绕并变为 -1;请参阅二进制补码。printf()
是一个变量参数函数。整型参数(例如char
)会自动提升为int
。因此,
printf()
看到值为-1
的int
,并相应地打印其十六进制表示形式。对于
unsigned
情况,没有环绕。printf()
看到值为255
的int
,并相应地打印其十六进制表示形式(省略前导零)。What you are seeing here is caused by two things:
255
does not fit in the range ofchar
(note that it is implementation-defined whetherchar
is equivalent tosigned char
orunsigned char
, but evidently on your platform it issigned char
). The resulting behaviour is implementation-defined, but typically it will wrap round and become -1; see two's complement.printf()
is a variable-argument function. Integral-type arguments (likechar
) are automatically promoted toint
.So
printf()
sees anint
with a value of-1
, and prints its hexadecimal representation accordingly.For the
unsigned
case, there is no wrap-around.printf()
sees anint
with a value of255
, and prints its hexadecimal representation accordingly (omitting the leading zeros).