HOWTO · Java
Java 右移 - >>>
本文介紹如何在 Java 中使用 >>> 運算子。
在 Java 語言中,>>> 通常被稱為無符號右移運算子。與有符號運算子不同,它始終允許尾隨位置填充零值。讓我們通過一個例子來理解下面的操作。
考慮兩個數 a 和 b。給定的兩個值如下。
a = 20
b = -20
a = 00000000000000000000000000010100
b = 11111111111111111111111111101100
按位右移運算子的用例是值除法或變數除以 2。
現在讓我們應用無符號右移運算子,即 a>>>1。運算子在內部將變數的所有位向右移動。它用零值填充尾隨位置。
下面是理解相同的程式碼塊。
public class RightShiftOperator {
public static void main(String[] args) {
System.out.println("The value of a and b before >>> operator");
int x = 20;
int y = -20;
System.out.println(Integer.toBinaryString(x));
System.out.println(Integer.toBinaryString(y));
System.out.println("The value of a and b after applying >>> operator");
System.out.println(Integer.toBinaryString(x >>> 1));
System.out.println(Integer.toBinaryString(y >>> 1));
int divX = x >>> 1;
int divY = y >>> 1;
System.out.println("Half the value of x: " + divX);
System.out.println("Half the value of y: " + divY);
}
}
在上面的程式碼塊中,變數 a 和 b 分別被初始化為值 20 和 -20。Integer 類的 toBinaryString() 函式應用於列印流方法。它的作用是將整數變數轉換為二進位制字串。該方法在 Java 1.2 版本中可用。Integer 類具有將主要 int 值轉換為相應包裝器物件的功能,因此充當原始值的包裝器。該方法的輸入是一個 int 變數,它將被轉換為 String 值。在函式中傳遞的引數是變數和運算子。最後,執行操作的變數被列印出來。
使用 >>>> 操作符的程式碼輸出如下。
The value of a and b before >>> operator
00000000000000000000000000010100
11111111111111111111111111101100
The value of a and b after applying >>> operator
00000000000000000000000000001010
01111111111111111111111111110110
Half the value of x: 10
Half the value of y: 2147483638