2013-03-18 34 views
1

鑑於以下代碼:位移問題

public class Something { 
public static void main(String[] args) { 
    int num = 1; 

    num <<= 32; 
    System.out.println(num); 

    num = 1; 
    for (int i = 0 ; i < 32; i++) 
     num <<= 1; 
    System.out.println(num); 
} 
} 

第一輸出(從NUM < < = 32)爲1

和(用於環路從)所述第二輸出是0。

我不明白它..它對我來說看起來是一樣的.. 兩種方法都將「1」數字(lsb)移動了32次,結果不同。

任何人都可以解釋嗎?

在此先感謝。

回答

5

任何人都可以解釋一下嗎?

絕對。基本上,int上的移位操作具有被屏蔽的右操作數以獲得範圍[0,31]中的值。 long上的移位操作會將其屏蔽以獲取範圍[0,63]中的值。

所以:

num <<= 32; 

等同於:

num <<= 0; 

section 15.19 of the JLS

如果左側操作數升級後的類型爲int,只有五個最低使用右側操作數的位數作爲移位距離。就好像右側的操作數受掩碼值0x1f(0b11111)的按位邏輯AND運算符&(第15.22.1節)的處理。實際使用的換檔距離總是在0到31的範圍內。

+0

有關更多詳細信息,請參見[JLS 15.19](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19)。 – 2013-03-18 19:18:22

+0

@LouisWasserman:是的,正在那裏:) – 2013-03-18 19:18:57

+0

完美。非常感謝你。得到它了。 – Rouki 2013-03-18 19:19:30

0

有關int,只有5 lowest order bits are used比特移位運算符。所以<< 32什麼都不做;它相當於<< 0,因爲32的最後5位是0.但循環中的<< 1操作每個都按預期執行。