为什么后面的移位操作不丢弃左移的位?

时间:2019-08-13 15:32:59

标签: c# bit-shift

假设我写了以下内容:

Console.WriteLine("{0:X8}", (uint)1 << 31);

它返回80000000(按预期方式)。

但是,如果我写了:

Console.WriteLine("{0:X8}", (uint)1 << 32);

它返回00000001

我希望“ 1”位被丢弃,结果为00000000

documentation在这里说:

  

左移操作将丢弃外部的高阶位   结果类型的范围并设置低位空位   位置为零。

的确,如果我写了这个:

Console.WriteLine("{0:X8}", (uint)0xFA << 28);

它返回A0000000F被丢弃)

1 个答案:

答案 0 :(得分:4)

来自同一documentation page

  

对于To solve it, just add the following line in your gradle.properties file: android.enableJetifier=true android.useAndroidX=true this should be in your build.gradle implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' Hope this will help. I resolved the issue by doing this x << count表达式,实际移位计数取决于x的类型,如下所示:

     
      
  • 如果x >> count的类型为int或uint,则移位计数由右侧操作数的低5位定义。也就是说,移位计数是根据x(或count & 0x1F)计算的。
  •   

count & 0b_1_111132 & 0x1F

此“陷阱”非常糟糕,以至于前C#设计团队成员Eric Lippert将其命名为the 8th worst C# feature