with
with

Reputation: 306

Unexpected C# bit shift right result

I underestimated the complexity of the >> operator; it's not doing what I thought it would.

I want to right shift a uint value of 6542454. I thought it worked like this:

val (is) == 11000111101010001110110
val >> 1 == 1100011110101000111011
val >> 2 == 110001111010100011101
val >> 3 == 11000111101010001110
val >> 4 == 1100011110101000111
val >> 5 == 110001111010100011
val >> 6 == 11000111101010001
val >> 7 == 1100011110101000

In reality, the results are:

val >> 1 == 1100011110101000111011
val >> 2 == 110001111010100011101
val >> 3 == 11111001100100110010011
val >> 4 == 1111100110010011001001
val >> 5 == 111110011001001100100
val >> 6 == 11111001100100110010
val >> 7 == 10011011111110111111100

The 3rd operation clearly does something I don't understand and things go off the rails from there. Seems to do the thing I don't understand again at the 7th operation as well.

Using the >>= operator 7 times in a row yields values I would expect:

val >>= 1 == 1100011110101000111011
val >>= 1 == 110001111010100011101
val >>= 1 == 11000111101010001110
val >>= 1 == 1100011110101000111
val >>= 1 == 110001111010100011
val >>= 1 == 11000111101010001
val >>= 1 == 1100011110101000

Why does val >> 3 not yield the same result as 3 calls to val >>= 1?

UPDATE:

My fault for using a decimal to binary converter on the web that was truncating my decimal input to 7 digits. When copy + pasting decimal values from Visual Studio, I didn't notice the truncation occurring.

The actual value being shifted is 654245426 and as everyone is correctly pointing out, C# is bit-shifting this value perfectly.

Upvotes: 4

Views: 770

Answers (1)

Matt Ellen
Matt Ellen

Reputation: 11592

I wrote code to output each shift:

uint i = 6542454;

for (int j = 0; j < 8; j++)
{
    uint k = i >> j;
    Console.WriteLine("{1} = {0}", Convert.ToString(k, 2), k);
}

and this is what I would expect to and did see.

6542454 = 11000111101010001110110
3271227 = 1100011110101000111011
1635613 = 110001111010100011101
817806 = 11000111101010001110
408903 = 1100011110101000111
204451 = 110001111010100011
102225 = 11000111101010001
51112 = 1100011110101000

Upvotes: 6

Related Questions