位操作 - 对于负数

Bit manipulation- for negative numbers

令整数i=-5的大小为2个字节。最左边的 signed bit 值为'1'(表示它是负数)。 当我尝试进行右移操作时,我不应该期望第 15 位位置的“1”移动到第 14 位吗?并给我一个高但积极的价值?

我尝试了什么:

int i=5;
i>>1 // giving me 2 (i understand this)

int i=-5
i>>1 // giving me -3 (mind=blown)

负值的右移是实现定义的,[expr.shift]/3

The value of E1 >> E2 is E1 right-shifted E2 bit positions. [..]. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

尽管大多数实现使用所谓的 arithmetic shift 它保留并扩展了符号位 :

Shifting right by n bits on a two's complement signed binary number has the effect of dividing it by 2n, but it always rounds down (towards negative infinity). This is different from the way rounding is usually done in signed integer division (which rounds towards 0). This discrepancy has led to bugs in more than one compiler.

那么当缩短到 8 位时,会发生以下情况。在二进制补码中 -5 将是

1111 1011

算术右移后:

1111 1101

现在翻转加一得到正值进行比较:

0000 0011 

我觉得像三。