📜  Java的按位右移运算符

📅  最后修改于: 2021-05-07 00:24:32             🧑  作者: Mango

在C / C++中,只有一个右移运算符“ >>”应仅用于正整数或无符号整数。在C / C++中,不建议对负数使用右移运算符,当将其用于负数时,输出取决于编译器(请参见此内容)。与C++不同, Java支持以下两个右移运算符。

1)>>(带符号右移)在Java,运算符’>>’是带符号右移运算符。所有整数都用Java签名,并且可以对负数使用>>。运算符“ >>”使用符号位(最左边的位)在移位后填充尾随位置。如果数字为负,则将1用作填充符,如果数字为正,则将0用作填充符。例如,如果数字的二进制表示形式为1 0….100,则使用>>右移2将其变为11 ….1。
请参阅以下Java程序作为示例“ >>”

class Test {
    public static void main(String args[])  {
       int x = -4;
       System.out.println(x>>1);   
       int y = 4;
       System.out.println(y>>1);   
    }    
}

输出:

-2
2

2)>>>(无符号右移)在Java,运算符’>>>’是无符号右移运算符。无论数字的符号如何,它始终填充0。

class Test {
    public static void main(String args[])  {
  
       // x is stored using 32 bit 2's complement form. 
       // Binary representation of -1 is all 1s (111..1)       
       int x = -1;  
  
       System.out.println(x>>>29);  // The value of 'x>>>29' is 00...0111
       System.out.println(x>>>30);  // The value of 'x>>>30' is 00...0011 
       System.out.println(x>>>31);  // The value of 'x>>>31' is 00...0001 
   }    
} 

输出:

7
3
1