Right shift operator used to check for negative numbers

I am trying to check the number is negative without using comparison operators. I am trying to learn the most significant bit. I do the following:

int x = -5;
Console.WriteLine(x >> 31);

I expected a way out 1. But I get it -1. What explains this behavior?

+4
source share
1 answer

This is because the operator >>on intbehaves as arithmetic shift: the bits are "inserted" take the value of the sign bit (either 0 or 1, 1 in your case). Thus, the resulting number is obtained 0xFFFFFFFF, that is -1.

From MSDN :

int long, ( ). uint ulong, ( ).

:

Console.WriteLine((uint)x >> 31);

, 0, - , : 1.

+6

Source: https://habr.com/ru/post/1533068/


All Articles