为什么下面的位移位操作没有丢弃向左移动的位?

Why is the following bitshift operation not discarding the bit shifted to the left?

假设我写了以下内容:

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

它returns 80000000(符合预期)。

但是,如果我写:

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

它returns 00000001.

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

这是 documentation 所说的:

The left-shift operation discards the high-order bits that are outside the range of the result type and sets the low-order empty bit positions to zero.

确实,如果我这样写:

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

它returnsA0000000F被丢弃)

来自同一个 documentation page:

For the x << count and x >> count expressions, the actual shift count depends on the type of x as follows:

  • If the type of x is int or uint, the shift count is defined by the low-order five bits of the right-hand operand. That is, the shift count is computed from count & 0x1F (or count & 0b_1_1111).

32 & 0x1F0.

这个 "gotcha" 已经够糟糕了,前 C# 设计团队成员 Eric Lippert 将其命名为 the 8th worst C# feature