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);
    }
}

在上面的代码块中,变量 ab 分别被初始化为值 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