Bit manipulation- for negative numbers

我是研究僧i 提交于 2019-12-11 03:05:46

问题


Let the size of integer i=-5 be 2 bytes. The signed bit value at the leftmost bit is '1'(which signifies that it is a negative number). When i am trying to do a right shift operation, should i not expect the '1' at the 15th bit position to shift to 14th position? and give me a high but positive value?

What i tried:

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

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

回答1:


Right shifts of negative values are implementation-defined, [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.

Most implementations use the so-called arithmetic shift though, which preserves and extends the sign-bit:

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.

So what happens is, when shortened down to 8 bit, the following. In two's complement -5 would be

1111 1011

After the arithmetic right shift:

1111 1101

Now flip and add one to get the positive value for comparison:

0000 0011 

Looks like a three to me.



来源:https://stackoverflow.com/questions/27954788/bit-manipulation-for-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!