why shift int a=1 to left 31 bits then to right 31 bits, it becomes -1

前端 未结 4 1228
别那么骄傲
别那么骄傲 2021-01-29 07:19

given

int a = 1; (00000000000000000000000000000001),

what I did is just

a=(a<<31)>>31;

4条回答
  •  灰色年华
    2021-01-29 07:45

    It is a signed shift so the left most bit will be extended. That way the overall number is on the same side of 0.

    By left shifting that much you put the lowest bit into the sign bit and end up with a negative number.

    When you then do a right shift it sign extends, copying the sign bit down to the lower 31 bits.

    If you want to know the lowest bit just do & 1.

提交回复
热议问题