有人可以解释一下如何在下面的程序中进行位移?

时间:2015-10-02 18:25:28

标签: java

public class Main {

      public static void main(String[] args){
          byte x = -7;
          System.out.println(x>>2);
          System.out.println(x>>>2);
      }

}

2 个答案:

答案 0 :(得分:1)

'>>'操作员右移保留标志,而'>>>'操作员在没有保留符号的情况下向右移动(零移位)。不能对Java中的字节执行位移,因此首先将其提升为int。

二进制中的-7(提升为int)是这样的:

11111111111111111111111111111001

使用'>>'向右移动两个运营商给我们:

11111111111111111111111111111110

小数为-2。现在使用'>>>'我们得到运营商:

00111111111111111111111111111110

,小数为1,073,741,822。

答案 1 :(得分:1)

>>>>>signed and unsigned right shift operators。与所有其他数字运算符一样,它们将对intlong值执行操作,因此byte在转换之前会隐式转换为int

您看到的二进制/十进制值是:

11111001                         // byte x = -7
11111111111111111111111111111001 // x as an int
11111111111111111111111111111110 // x >> 2
00111111111111111111111111111110 // x >>> 2
-2         // 11111111111111111111111111111110 in decimal
1073741822 //   111111111111111111111111111110 in decimal