[英]When I input a number in char type, why i can't get a whole number?
[英]I can't understand why I get this result when I bitwise OR a short and char
有人可以解释为什么我按位或两个数字时得到这个结果吗? 我真的很困惑
signed char signedChar = -64; // This is now -64, or 1100 0000
unsigned char unsignedChar = signedChar; // This is now 196, or 1100 0000 (The same)
short signedShort = 0; // This is now 0000 0000 0000 0000
signedShort |= signedChar; // This is now -64, not 196
我期望发生的事情是,我签署了signedShort和signedChar,这是:
0000 0000 0000 0000 or'ed with
1100 0000
0000 0000 1100 0000 result
equalling 196.
但是我得到了-64
为什么此OR操作在开始时添加一个? 我完全期望有所不同。
谢谢。
表达式signedShort |= signedChar;
被解释为
signedShort = signedShort | signedChar;
|
两个操作数 将运算符提升为int
,对这些提升的值执行按位或运算,结果转换为目标的类型short
。
因此, signedChar
, -64
的值被扩展为具有相同值的int
。 或为0
不会更改该值。 将其转换为short
也会保留该值,因为-64
在short
范围内,因此结果为-64
。
请注意,这不依赖于整数的实际表示。 您假设问题中有2s补码,但是以正负号或1s补码会产生相同的结果。
具有负值的带符号类型将以1扩展。 无符号类型将以零扩展。
您未签名的字符将被提升为已签名,因为这就是您执行操作所要使用的字符。
已签名是未签名的促销
在您的示例中:
0000 0000 0000 0000 or'ed with
1111 1111 1100 0000
1111 1111 1100 0000 result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.