繁体   English   中英

我不明白为什么我按位或short和char会得到这个结果

[英]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也会保留该值,因为-64short范围内,因此结果为-64

请注意,这不依赖于整数的实际表示。 您假设问题中有2s补码,但是以正负号或1s补码会产生相同的结果。

具有负值的带符号类型将以1扩展。 无符号类型将以零扩展。

您未签名的字符将被提升为已签名,因为这就是您执行操作所要使用的字符。

已签名是未签名的促销

在您的示例中:

0000 0000 0000 0000 or'ed with
1111 1111 1100 0000
1111 1111 1100 0000 result

基本上就是二进制补码算法的工作原理。 为了保留值的符号,在转换过程中将应用特殊的符号扩展

让我们以-10的简单示例为例:

signed char signedChar = -10; // bits: 11110110b
signed short signedShort = signedChar; // bits: 1111111111110110b

为什么不像您期望的那样显示1000000000000110b? 因为1000000000000110b是-32762的二进制补码:-(

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM