That's because operator >>
on an int
behaves as an arithmetic shift: the bits that are "pushed in" take the value of the sign bit (either 0 or 1, 1 in your case). So the resulting number you get is 0xFFFFFFFF
, that is -1
.
From MSDN:
If the first operand is an int or long, the right-shift is an arithmetic shift (high-order empty bits are set to the sign bit). If the first operand is of type uint or ulong, the right-shift is a logical shift (high-order bits are zero-filled).
If you do:
Console.WriteLine((uint)x >> 31);
This is a logical shift, the higher bits are filled with 0
, and the output is the one you expected: 1
.