我在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
輕鬆谷歌搜索可以給你答案。 – Vladp 2014-11-06 16:49:59
問:「爲什麼X語言會這樣做?」答:因爲規格如此。 – Durandal 2014-11-06 16:56:18
很好的常識來了,所以我沒有想到檢查規範,它說:(16 >> 1)32次只會取得與(16 >> 32)相同的結果一次。 – abhishek08aug 2014-11-06 18:04:51