0
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?

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

2 Answers2

2

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    A `>>` _is not_ a division, it is a shift. Only without cycling is the result the same as from a division. – H H Oct 27 '12 at 10:01
  • correct, I supposed that this is *not* about cycling, but looking on edited answer saw it. editing. – Tigran Oct 27 '12 at 10:04
  • @AlanDert: is seems **to me** that: or it's not complete hint from the book, or there is a typo in the book, cause the *code provided* can not be correct, imo. – Tigran Oct 27 '12 at 10:10
1
(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#?

Community
  • 1
  • 1
wdavo
  • 5,070
  • 1
  • 19
  • 20