Sign extension with bitwise shift operation

前端 未结 5 1308
小蘑菇
小蘑菇 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:08

    Becaue t is either 0 or -1, ~t is also always -1 or 0.

    This is due to the (implementation defined) behaviour or (i - 128) >> 31, which essentially copies the top bit of (i-128) [assuming 32-bit integers]. If i is > 128, it will result in a zero in the top bit. If i is less than 128, the result is negative, so the top bit is set.

    Since ~t is "all bits opposite of t", you can expect that t is always 0xffffffff if t is zero.

提交回复
热议问题