given
int a = 1;
(00000000000000000000000000000001
),
what I did is just
a=(a<<31)>>31;
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 1
s 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.