代碼
package com.ggp.test.Third;
/**
* @Author:ggp
* @Date:2019/7/27 17 23
* @Description:
*/
public class URShift {
public static void main(String[] args) {
byte b = -1;
System.out.println(Integer.toBinaryString(b));
System.out.println(Integer.toBinaryString(b>>>10));
System.out.println(b>>>10);
byte c = -1;
System.out.println(Integer.toBinaryString(c));
c>>>=10;
System.out.println(Integer.toBinaryString(c));
System.out.println(c);
}
}
運行結果
11111111111111111111111111111111
1111111111111111111111
4194303
11111111111111111111111111111111
11111111111111111111111111111111
-1
Process finished with exit code 0
剛開始我很不理解爲什麼會有不同的輸出,這兩種的輸入區別在哪裏?
通過仔細觀察我弄懂了原因。
第一種和第二種相比,第二種其實多了一步轉類型。
首先short和byte在java中其實是以32字節的方式存儲的,也就是相當於一個int
第一種,b>>>10
首先b會轉成int然後右移10位變成
11111111 11111111 11111111 11111111 》》 00000000 00111111 11111111 11111111
因爲本身就是int 打印結果就是11111 11111111 11111111
第二種,b>>>10之後還會進行轉型
11111111 11111111 11111111 11111111 》》 00000000 00111111 11111111 11111111 》》11111111 11111111
打印的時候在轉int 》》11111111 11111111 11111111 11111111