C# 中左移位的奇怪行为

Weird behaviour with left bitwise shift in C#

测试此代码时

 for (int i = 0; i <= 32; i++)
 {
     Console.WriteLine(i + " - " + ((byte.MaxValue + 1) << i));
 }

我得到这些输出

0 - 256
1 - 512
2 - 1024
3 - 2048
4 - 4096
5 - 8192
6 - 16384
7 - 32768
8 - 65536
9 - 131072
10 - 262144
11 - 524288
12 - 1048576
13 - 2097152
14 - 4194304
15 - 8388608
16 - 16777216
17 - 33554432
18 - 67108864
19 - 134217728
20 - 268435456
21 - 536870912
22 - 1073741824
23 - -2147483648
24 - 0
25 - 0
26 - 0
27 - 0
28 - 0
29 - 0
30 - 0
31 - 0
32 - 256

请注意,从 21 到 31,它给出了 0,这是预期的行为,但是在 32,我得到了数字 256。

我预计 32 会是 0,但如您所见,我得到的是 256。有人能给我一些关于 dot NET 运行时在看到左移 32 时正在做什么的见解吗?

它实际上在 C# 语言规范中:

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.

也在MSDN:

If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. That is, the actual shift count is 0 to 31 bits.

因此将 int 移动 32 与将其移动零完全相同。