为什么我会通过负值移位奇怪的结果?

时间:2009-12-10 14:49:11

标签: c# bit-shift

此问题与this question不重复。

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

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

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

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

任何人都可以解释这种行为吗?

这是一个小小的奖励。我将左移改为右移,得到了这个输出:

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

2 个答案:

答案 0 :(得分:15)

你不能换负值。你也不能换一个大的正数。

来自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.

答案 1 :(得分:8)

在类似C语言的<< -1中,>> 1不会转换为-1。取而代之的是最不重要的5位移位,其余的被忽略,因此在这种情况下,两个补码<< 31转换为javascript:alert(8<<-8)

你会从例如得到相同的结果。 JavaScript {{1}}。