Sign extension with bitwise shift operation

前端 未结 5 1272
小蘑菇
小蘑菇 2021-01-06 02:23

following this Q&A I tried to exam the answer so I wrote:

#include 

int main ()
{

        int t;int i;
        for (i=120;i<140;i++){         


        
5条回答
  •  走了就别回头了
    2021-01-06 03:01

    Why does t = (i - 128) >> 31 gives zero or -1 for each number?

    When a non-negative 32-bit integer is shifted right 31 positions, all non-zero bits get shifted out and the most significant bits get filled with 0, so you end up with 0.

    Usually, when a negative 32-bit integer is shifted right 31 positions, the most significant bits don't get filled with 0, instead they get set to the sign of the number and so the sign propagates into all bits and in 2's complement representation all bits set to 1 amount to -1. The net effect is as if you repeatedly divided the number by 2, but with a little twist... The result is rounded towards -infinity instead of towards 0. For example -2>>1==-1 but -3>>1==-2 and -5>>1==-3. This is called arithmetic right shift.

    When I say "usually", I mean the fact that the C standard allows several different behaviors for right shifts of negative values. On top of that, it allows non-2's complement representations of signed integers. Usually, however, you have the 2's complement representation and the behavior that I've showed/explained above.

提交回复
热议问题