Question

I am trying to check of a number is negative without using comparison operators. I am trying to examine the most significant bit. I am doing the following :

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

I was expecting the output to be 1. But I get -1. What explains this behavior?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top