C语言 无符号字符的最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3373540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Maximum value of unsigned char
提问by Variance
#include <stdio.h>
int main()
{
unsigned char i=0x80;
printf("%d",i<<1);
return 0;
}
Why does this program print 256?
为什么这个程序打印 256?
As I understand this, since 0x80= 0b10000000, and unsigned char has 8 bits, the '1' should overflow after left shift and the output should be 0, not 256.
据我了解,由于 0x80=0b10000000,并且 unsigned char 有 8 位,“1”应该在左移后溢出,输出应该是 0,而不是 256。
回答by Billy ONeal
This is a result of C's integer promotion rules. Essentially, most any variable going into an expression is "promoted" so that operations like this do not lose precision. Then, it's passed as an intinto printf, according to C's variable arguments rules.
这是 C 的整数提升规则的结果。从本质上讲,大多数进入表达式的任何变量都被“提升”,以便像这样的操作不会失去精度。然后,根据 C 的可变参数规则,它作为一个intinto传递printf。
If you'd want what you're looking for, you'd have to cast back to unsigned char:
如果你想要你正在寻找的东西,你必须回到unsigned char:
#include <stdio.h>
int main()
{
unsigned char i=0x80;
printf("%d",((unsigned char)(i<<1)));
return 0;
}
Note: using %cas specified in Stephen's comment won't work because %cexpects an integer too.
注意:%c按照斯蒂芬的评论中指定的方式使用将不起作用,因为也%c需要一个整数。
EDIT: Alternately, you could do this:
编辑:或者,你可以这样做:
#include <stdio.h>
int main()
{
unsigned char i=0x80;
unsigned char res = i<<1;
printf("%d",res);
return 0;
}
or
或者
#include <stdio.h>
int main()
{
unsigned char i=0x80;
printf("%d",(i<<1) & 0xFF);
return 0;
}
回答by Paul E.
Don't forget the format specifically for printing unsigned.
不要忘记专门用于打印未签名的格式。
printf("%u",(unsigned char)(i<<1));

