2014-11-06 97 views
3

我在java中使用右移運算符時遇到了一個奇怪的情況。當我右移16乘31時,結果爲0,但是在嘗試右移16乘32時,它仍然是16。有人可以解釋它,因爲我瘋了。爲什麼在Java中右移16乘32將導致16而不是0? 16 >> 32 = 16爲什麼?

public class RightShiftTest { 

    public static void main(String args[]) {   
     int b = 16; 
     System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b)); 

     // As expected it is 0 
     System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31)); 

     // But why is it not 0 but 16 
     System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32)); 
    }  
} 

Output: 
Bit pattern for int 16 is 10000 
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0 
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000 
+1

輕鬆谷歌搜索可以給你答案。 – Vladp 2014-11-06 16:49:59

+1

問:「爲什麼X語言會這樣做?」答:因爲規格如此。 – Durandal 2014-11-06 16:56:18

+0

很好的常識來了,所以我沒有想到檢查規範,它說:(16 >> 1)32次只會取得與(16 >> 32)相同的結果一次。 – abhishek08aug 2014-11-06 18:04:51

回答

9

Java Language Specification狀態

如果左邊的操作數的提升的類型是int只有五個右手操作數的 最低階位被用作移位 距離。這是因爲如果在右邊的操作數進行與掩模值0x1f0b11111)(§15.22.1)一個 逐位邏輯AND運算&。實際使用的偏移距離因此總是在 範圍0至31(含)之間。最低5位是00000這樣0,由0比特移位

值32被表示爲

100000 

+0

很好的迴應!非常感謝。 – abhishek08aug 2014-11-06 18:00:20

+0

如果您的問題已得到解答,請[請標記您認爲您的問題已被接受的答案](http://stackoverflow.com/help/someone-answers),而不是發表評論感謝回答者。一旦你有至少15個代表,你也可以[upvote](http://stackoverflow.com/help/why-vote)接受的答案和其他你認爲有用的答案。 – 2014-11-07 04:19:35

相關問題