Java中的按位右移运算符
Java支持两种类型的右移运算符。>>运算符是有符号的右移运算符,而>>>是无符号的右移运算符。左操作数的值向右移动右操作数指定的位数。
签名右移运算符
带符号的右移运算符“>>”使用符号位填充尾随位置。例如,如果数字为正,则将使用0填充尾随位置,如果数字为负,则将使用1填充尾随位置。
假设a=60和b=-60;现在为二进制格式,它们将如下所示-
a = 0000 0000 0000 0000 0000 0000 0011 1100 b = 1111 1111 1111 1111 1111 1111 1100 0100
在Java中,负数存储为2的补数。
Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110 And b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010
无符号右移运算符
无符号右移运算符“>>”不使用符号位来填充尾随位置。它总是以0s填充尾随位置。
Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110 And b >>> 1 = 0111 1111 1111 1111 1111 1111 1110 0010
示例
public class Tester {
public static void main(String[] args) {
int a = 60; int b = -60; int c = 0;
System.out.println("60 = " + Integer.toBinaryString(a));
System.out.println("-60 = " + Integer.toBinaryString(b));
//有符号移位
c = a >> 1;
System.out.println("60 >> 1 = " + Integer.toBinaryString(c));
//un有符号移位
c = a >>> 1;
System.out.println("60 >>> 1 = " + Integer.toBinaryString(c) );
c = b >> 1;
System.out.println("-60 >> 1 = " + Integer.toBinaryString(c) );
c = b >>> 1;
System.out.println("-60 >>> 1 = " + Integer.toBinaryString(c));
}
}输出结果
60 = 111100 -60 = 11111111111111111111111111000100 60 >> 1 = 11110 60 >>> 1 = 11110 -60 >> 1 = 11111111111111111111111111100010 -60 >>> 1 = 1111111111111111111111111100010
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短