2009-12-10 64 views
9

此問題不是this question的重複。爲什麼我得到一個奇怪的結果位移負值?

我遇到了一種情況,我可能不得不左移一個負值,即8 < < -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

回答

12

你不能移動一個負值。你也不能移動一個大的正數。

從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. 
8

<< -1不轉化爲>> 1類似C語言。取而代之的是移位的最低有效位5位被忽略,所以在這種情況下,二進制補碼-1轉換爲<< 31

你會從例如。 JavaScript javascript:alert(8<<-8)

相關問題