7

An Int64 variable needs to be shifted. I am parsing pseudo mathematical functions from a database file. The Variables are uint32 or int32 so i did put them into an Int64 to handle them equally without loosing anything. In one of my treenodes i need to bitshift Int64.

Unfortunately the shift operator does not apply to Int64. Is there a standard way of bit shifting Int64 that i am not aware of?

//Int32 Example works
int a32 = 1;
int b32 = 2;
int c32 = a32 >> b32;

//Int64 Example does not compile
Int64 a64 = 1;
Int64 b64 = 2;
Int64 c64 = a64 >> b64; //invalid operator
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Johannes
  • 6,490
  • 10
  • 59
  • 108

2 Answers2

17

I believe the right-hand operand of the right-shift operator (in C#) always takes an int, even if the left-hand operand is not an int.

Official details here in C# Specification on MSDN.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
reuben
  • 3,360
  • 23
  • 28
  • 7
    Nothing else would make sense, since shifting more than 64 places just shifts everything out of existence anyway. – Dervall Jul 05 '12 at 11:50
  • 2
    @Dervall But along those lines, even an `int` is overkill too :) – reuben Jul 05 '12 at 11:53
  • @reuben a byte would do, but that would cause slower code since the processor is optimized to work with 32 bits, or 64 bits. – Dervall Jul 05 '12 at 11:55
  • ok - it works with an int... but theretically my users could write UINT32.MAX as a value and my code would do something stupid... i admit its unlikely.. i will leave a TODO in my code to drive future programmers mad. – Johannes Jul 05 '12 at 16:33
9

The number of bits to be shifted must be an int.

Eg:

int shift = 3;
long foo = 123456789012345;
long bar = foo >> shift;
leppie
  • 115,091
  • 17
  • 196
  • 297