C#: Shift left assignment operator behavior

送分小仙女□ 提交于 2019-12-07 04:29:30

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/2505550/c-shift-left-assignment-operator-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!