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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。