Bit-shifting with Int64
Asked Answered
H

2

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
Hymettus answered 5/7, 2012 at 11:46 Comment(4)
Can you just store b64 as int? Will it make a difference?Lidalidah
could you use UInt64 (unsigned int)?Adams
the right hand operand is the number of bits to shift the left hand operand. so shifting by an Int64 makes no sense...Doorstone
@codesparkle i agree, but a number like that could come from the database. i solved it now by converting to int32.Hymettus
K
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.

Kinnard answered 5/7, 2012 at 11:48 Comment(4)
Nothing else would make sense, since shifting more than 64 places just shifts everything out of existence anyway.Entrap
@Entrap But along those lines, even an int is overkill too :)Kinnard
@Kinnard a byte would do, but that would cause slower code since the processor is optimized to work with 32 bits, or 64 bits.Entrap
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.Hymettus
W
9

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

Eg:

int shift = 3;
long foo = 123456789012345;
long bar = foo >> shift;
Weinhardt answered 5/7, 2012 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.