12

这个问题不是这个问题的重复。

我遇到了一种情况,我可能不得不将(正)数左移一个负值,即 8 << -1。在这种情况下,我希望结果为 4,但我以前从未这样做过。所以我编写了一个小测试程序来验证我的假设:

for (int i = -8; i <= 4; i++)
    Console.WriteLine("i = {0}, 8 << {0} = {1}", i, 8 << i);

令我震惊和惊讶的是,这给了我以下输出:

我 = -8, 8 << -8 = 134217728
我 = -7, 8 << -7 = 268435456
我 = -6, 8 << -6 = 536870912
我 = -5, 8 << -5 = 1073741824
我 = -4, 8 << -4 = -2147483648
我 = -3, 8 << -3 = 0
我 = -2, 8 << -2 = 0
我 = -1, 8 << -1 = 0
我 = 0, 8 << 0 = 8
我 = 1, 8 << 1 = 16
我 = 2, 8 << 2 = 32
我 = 3, 8 << 3 = 64
我 = 4, 8 << 4 = 128

谁能解释这种行为?

这是一个小红利。我将左移更改为右移,并得到以下输出:

我 = -8, 8 >> -8 = 0
我 = -7, 8 >> -7 = 0
我 = -6, 8 >> -6 = 0
我 = -5, 8 >> -5 = 0
我 = -4, 8 >> -4 = 0
我 = -3, 8 >> -3 = 0
我 = -2, 8 >> -2 = 0
我 = -1, 8 >> -1 = 0
我 = 0, 8 >> 0 = 8
我 = 1, 8 >> 1 = 4
我 = 2, 8 >> 2 = 2
我 = 3, 8 >> 3 = 1
我 = 4, 8 >> 4 = 0
4

2 回答 2

18

您不能移动负值。你也不能移动一个很大的正数。

从 C# 规范(http://msdn.microsoft.com/en-us/library/a1sway8w.aspx):

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

...


The high-order bits of first operand are discarded and the low-order 
empty bits are zero-filled. Shift operations never cause overflows.
于 2009-12-10T14:54:28.507 回答
12

在类 C 语言<< -1中不会翻译为>> 1. 取而代之的是移位的最低有效 5 位,其余的被忽略,因此在这种情况下,二进制补码-1转换为<< 31.

您将从例如获得相同的结果。JavaScript javascript:alert(8<<-8)

于 2009-12-10T15:00:23.473 回答