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

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

given

int a = 1; (00000000000000000000000000000001),

what I did is just

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

4条回答
  •  别那么骄傲
    2021-01-29 07:42

    What you are missing is that in C++ right shift >> is implementation defined. It could either be logical or arithmetic shift for a signed value. In this case it's shifting in 1s from the left to retain the sign of the shifted value. Typically you want to avoid doing shifts on signed values unless you know precisely that they will be positive or that the shift implementation doesn't matter.

提交回复
热议问题