Alan Coromano
Alan Coromano

Reputation: 26048

Shift displacement returns a wrong result

Console.WriteLine(7 << 4);
Console.WriteLine(7 >> (32 - 4));

For some reason the second method returns 0 instead of 112. But they both should be equal to one another, they both should return 112.

UPDATE: It's known that (x << n) == (x >> (32 - n)).

Your ideas?

Upvotes: 0

Views: 97

Answers (2)

wdavo
wdavo

Reputation: 5110

(x << n) == (x >> (32 - n))

This is only true if it is a circular shift being performed, which isn't the case in C#. In C# they bits are lost if the are shifted right past the first bit.

//Seven = 00000111
Console.WriteLine(7 >> 1);  //00000011
Console.WriteLine(7 >> 2);  //00000001
Console.WriteLine(7 >> 3);  //00000000
Console.WriteLine(7 >> 4);  //00000000
//.
//.
//.
Console.WriteLine(7 >> 28);  //00000000

Explained in more detail here: Is there a way to perform a circular bit shift in C#?

Upvotes: 1

Tigran
Tigran

Reputation: 62276

Don't really understand what you expect to see here:

7 << 4 is shifting left (like multiplication) 7 * (2 ^ 4) = 7 * 16 = 112

on another hand

7 >> (32 - 4) is shifting right (like division)7/(2^28), that converted to integer value leads to 0.

The question is why Console.WriteLine peaks integer overload: is cause you act on integer values so expected by CLR result is int.

So result is correct.

Upvotes: 2

Related Questions