2

I am confused why does this produce 0xffffffff in C#, I was expecting it to produce 0x0. The type of the expression is uint.

Console.WriteLine(0xffffffff >> 32);
user3700562
  • 693
  • 11
  • 23
  • Why did you expect `0x0`? – mjwills Dec 07 '18 at 12:15
  • because all bits get shifted out to the right and the type is unsigned so should be filled with zeros from the left. the same expression yields 0 in c. – user3700562 Dec 07 '18 at 12:16
  • https://codeyarns.com/2004/12/20/c-shift-operator-mayhem/ tells me c is not perfect on this, too. At least when it comes to shifting 32 bits, also see here https://stackoverflow.com/questions/12145636/bit-shifting-an-int-32-times-in-c they call it undefined behaviour. – FrankM Dec 07 '18 at 12:25
  • btw, why would you need to shift out all of the digits? could you not logically combine it to the max or min value with or/and? – FrankM Dec 07 '18 at 12:27
  • Interesting Fact: ```Console.WriteLine(0xffffffff >> 31>>1);``` produces 0, as you wished – FrankM Dec 07 '18 at 12:32

1 Answers1

4

As per the documentation:

If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).

The second operand is 32. 32 & 0x1f is 0. Thus >> 32 is equivalent to 'shift this by 0 bits' therefore 'do nothing at all'.

mjwills
  • 23,389
  • 6
  • 40
  • 63