简体   繁体   English

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

[英]I can't understand why I get this result when I bitwise OR a short and char

Could someone please explain why I get this result when I bitwise OR two numbers? 有人可以解释为什么我按位或两个数字时得到这个结果吗? I'm really confused. 我真的很困惑

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 

What I expected to happen was this, I or'ed signedShort and signedChar, which is: 我期望发生的事情是,我签署了signedShort和signedChar,这是:

0000 0000 0000 0000 or'ed with
          1100 0000
0000 0000 1100 0000 result 
equalling 196.

But instead I got -64 但是我得到了-64

Why does this OR operation add a one at the beginning? 为什么此OR操作在开始时添加一个? I totally expected something different. 我完全期望有所不同。

Thanks. 谢谢。

The expression signedShort |= signedChar; 表达式signedShort |= signedChar; is interpreted as 被解释为

signedShort = signedShort | signedChar;

Both operands of the | |两个操作数 operator are promoted to int , the bitwise or operation is performed on these promoted values and the resulted is converted to the type of the destination, short . 将运算符提升为int ,对这些提升的值执行按位或运算,结果转换为目标的类型short

Hence the value of signedChar , -64 is extended as an int with the same value. 因此, signedChar-64的值被扩展为具有相同值的int Or-ing to 0 does not change the value. 或为0不会更改该值。 Converting it to short also keeps the value because -64 is within the range of short , so the result is -64 . 将其转换为short也会保留该值,因为-64short范围内,因此结果为-64

Note that this does not depend on the actual representation of integers. 请注意,这不依赖于整数的实际表示。 You assume 2s complement in your question, but it would produce the same result with sign+magnitude or 1s complement. 您假设问题中有2s补码,但是以正负号或1s补码会产生相同的结果。

Signed types with negative values will be extended with ones. 具有负值的带符号类型将以1扩展。 An unsigned type will be extended with zeros. 无符号类型将以零扩展。

Your unsigned char gets promoted to signed, since that is what you are performing operations with. 您未签名的字符将被提升为已签名,因为这就是您执行操作所要使用的字符。

Signed is a promotion from unsigned 已签名是未签名的促销

In your example: 在您的示例中:

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

That is how basically Two's complement arithmetic works. 基本上就是二进制补码算法的工作原理。 To preserve sign of a value, a special operation Sign extension is applied during conversion. 为了保留值的符号,在转换过程中将应用特殊的符号扩展

Let's take a simpler example of -10: 让我们以-10的简单示例为例:

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

Why not 1000000000000110b as you seem expected it to be? 为什么不像您期望的那样显示1000000000000110b? Because 1000000000000110b is -32762 in two's complement :-( 因为1000000000000110b是-32762的二进制补码:-(

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

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