繁体   English   中英

二进制运算符<<是什么意思?

[英]What does the binary operator << mean?

在Java中,有>>,<<和>>>运算符。

根据Java doc

有符号的左移位运算符“ <<”将位模式向左移位,而有符号的右移位运算符“ >>”将位模式向右移位。 位模式由左操作数给出,移位位置的数量由右操作数给出。 无符号右移运算符“ >>>”将零移位到最左位置,而“ >>”之后的最左位置取决于符号扩展名。

我是二进制数据的新手,但我发现这种解释有点含糊,没有示例或用例。 有人可以给我这些操作员的例子或用例吗?

谢谢,

Java文档

有符号的左移位运算符“ <<”将位模式向左移位,而有符号的右移位运算符“ >>”将位模式向右移位。 位模式由左操作数给出,移位位置的数量由右操作数给出。 无符号右移运算符“ >>>”将零移位到最左位置,而“ >>”之后的最左位置取决于符号扩展名。

    public class Test {

      public static void main(String args[]) {
         int a = 60;    /* 60 = 0011 1100 */  
         int b = 13;    /* 13 = 0000 1101 */
         int c = 0;

         c = a << 2;     /* 240 = 1111 0000 */
         System.out.println("a << 2 = " + c );
    //this will shift the binary version of a to two bits left side and insert zero in remaining places
         c = a >> 2;     /* 215 = 1111 */
         System.out.println("a >> 2  = " + c );
    //this will shift the binary version of a to left by two bits right  insert zero in remaining places
         c = a >>> 2;     /* 215 = 0000 1111 */
         System.out.println("a >>> 2 = " + c );
//this will shift the binary of a to 3bits right  insert zero in remaining places
      }
    } 

我们有以下十进制和二进制数字:

8 = 0000 1000

15 = 0000 1111

10 = 0000 1010

然后,我们使用<<操作符,得到以下结果:

8 << 1-> 0001 0000 = 16

15 << 2-> 0011 1100 = 60

10 << 1-> 0001 0100 = 20

如您所见,运算符将数字的二进制表示形式移位右操作数给出的位数。 这样做,您将获得一个新号码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM