有符号和无符号数据类型之间的区别?
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)
您在这里看到的情况是由两件事引起的:
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).C 编译器必须扩展传递给 printf 的值(这称为“提升”),因为 printf 是一个可变参数函数(可以使用不同的参数调用它)。对于
char
类型的值,提升后的值为int
类型。由于编译器的char
类型似乎是有符号的,因此提升的值是符号扩展的。在二进制中:在无符号的情况下,不会发生符号扩展:
The C compiler has to expand the value passed to
printf
(this is called "promotion"), becauseprintf
is a variadic function (it can be called with differing arguments). For values of typechar
, the promoted value is of typeint
. Since your compiler'schar
type seems to be signed, the promoted value is sign extended. In binary:In the unsigned case, no sign-extension happens:
char i = 255;
通过将值转换为不适合的有符号类型来调用实现定义的行为(假设char
只有 8 位且纯char
是有符号的,两者也是特定于实现的。char i = 255;
invokes implementation-defined behavior by converting a value to a signed type into which it does not fit (assumingchar
is only 8 bits and plainchar
is signed, both of which are also implementation-specific.当您将 8 位有符号变量设置为值 255 时,它无法保存该值,在这种情况下,它似乎将负(高端)标志设置为 1,因此如果有符号,该值将为 -1 ,但随后它会转换为整数 -1,即
ffffffff
。When you set an 8-bit signed variable to the value 255, which it can't hold, it seems in this case it sets the negative (high-end) flag to 1, so the value would be -1 if it were signed, but then it gets converted to an integer -1 which is
ffffffff
.