我无法理解为什么当我按位或短和char时我得到这个结果

Zeb*_*ish 2 c c++ bits bit-manipulation

有人可以解释为什么我在按位或两个数字时得到这个结果?我真的很困惑.

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 
Run Code Online (Sandbox Code Playgroud)

我预计会发生这种情况,我或者签署了短期签署的协议,这是:

0000 0000 0000 0000 or'ed with
          1100 0000
0000 0000 1100 0000 result 
equalling 196.
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了-64

为什么这个OR操作在开头添加一个?我完全期待不同的东西.

谢谢.

chq*_*lie 6

表达式signedShort |= signedChar;被解释为

signedShort = signedShort | signedChar;
Run Code Online (Sandbox Code Playgroud)

操作|符的两个操作数都被提升为int,对这些提升的值执行按位或操作,并将结果转换为目标的类型,short.

因此的值signedChar,-64被扩展为int具有相同的值.或者0不改变值.转换它short也保持值,因为-64它在范围内short,所以结果是-64.

请注意,这不依赖于整数的实际表示.你在你的问题中假设2s补码,但它会产生相同的符号+幅度或1s补码的结果.