Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Shift left assignment operator behavior

I'm running code that sometimes yields this:

UInt32 current;  
int left, right;  

...

//sometimes left == right and no shift occurs
current <<= (32 + left - right);

//this works
current <<= (32 - right);
current <<= left;

It appears for any value >= 32, only the value % 32 is shifted. Is there some "optimization" occurring in the framework?

like image 934
Austin Salonen Avatar asked Mar 24 '10 05:03

Austin Salonen


1 Answers

C# 3.0 language specification, 7.8 "Shift operators":

For the predefined operators, the number of bits to shift is computed as follows:

  • When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.
  • When the type of x is long or ulong, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F.
like image 113
Pavel Minaev Avatar answered Oct 20 '22 14:10

Pavel Minaev