有符号字符的无符号字符输出 [英] unsigned char output of a signed char

查看:50
本文介绍了有符号字符的无符号字符输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

char x = -1;
int y = x;

printf("%u\n", x);
printf("%u\n", y);

输出为:

4294967295
4294967295

我不明白为什么 x 可以得到这样的值.我知道无符号字符的最大值是 255,有符号字符的最大值是 127.怎么可能是 4294967295?

I dont understand why x can get such a value. I know that the maximum value of a unsigned char is 255 and for a signed char 127. How can it be 4294967295?

推荐答案

对于像 printf 这样使用可变参数的函数,任何小于 int (int>char 和 short) 被隐式提升为 int.浮点数也是一样,float被提升为double.

For functions like printf that use variadic arguments, any integral types smaller than an int (char and short) are implicitly promoted to int. The same is true with floating-point numbers, float is promoted to double.

因此,您的 char 被符号扩展为值为 -1int,并且由于您将其打印为无符号,在 2 的补码中你得到 UINT_MAX.

Hence, your char is being sign-extended to an int with value -1, and since you are printing it as unsigned, in 2's complement you get UINT_MAX.

正如下面的 chux 注释,如果您的 char 默认为无符号(这取决于您的编译器/平台),则答案将改为 255.当发生提升时,该值将被零扩展而不是符号扩展.

as chux notes below, if your char defaulted to unsigned (this depends on your compiler/platform), the answer would be 255 instead. When promotion occurs, the value will be zero-extended instead of sign-extended.

这篇关于有符号字符的无符号字符输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆