有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的双大于号(>>)?

>>符号在Java中是什么意思?我以前从未见过它被使用过,但今天偶然发现了它。我试着在谷歌上搜索,但没有找到任何有用的东西


共 (6) 个答案

  1. # 1 楼答案

    这是位移位运算符Documentation

    The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

  2. # 2 楼答案

    它改变了位

    这里有一些关于java operators的信息

    比如说

    101  = 5
    Shifting out the right "1"
    10 = 2
    Shifting the other way...
    1010 = 10
    
  3. # 3 楼答案

    这是一个右移

  4. # 4 楼答案

    右移:

    右换档操作员,>>;,将值中的所有位向右移位指定次数。 其一般形式为:价值>&燃气轮机;号码 在这里,num指定要在值中右移值的位置数。即>&燃气轮机;将指定值中的所有位向右移动num指定的位位置数。 下面的代码片段将值32向右移动两个位置,从而将a设置为8:

    int a = 32;
    a = a >> 2; // a now contains 8
    

    当一个值的位被“移开”时,这些位将丢失。例如,下一个代码片段将值35向右移动两个位置,这会导致两个低阶位丢失,导致a再次被设置为8

    int a = 35;
    a = a >> 2; // a still contains 8
    

    查看二进制中的相同操作可以更清楚地显示这是如何发生的:

    00100011 35 >> 2
    00001000 8
    

    每次向右移动一个值时,它都会将该值除以2,并丢弃任何余数。您可以利用这一点进行高性能整数除以2。当然,您必须确保没有从右端移动任何位。 右移时,右移显示的顶部(最左侧)位将用顶部位的先前内容填充。这称为符号扩展,用于在将负数向右移动时保留负数的符号。例如,–8 >> 1–4,它在二进制中是

    11111000 –8 >>1
    11111100 –4
    

    有趣的是,如果将–1右移,结果始终保持–1,因为符号扩展会在高阶位中不断引入更多的1。 有时,将扩展值向右移动时,不希望对其进行签名。例如,以下程序将字节值转换为其十六进制字符串表示形式。请注意,移位的值通过与0x0f进行ANDing来屏蔽,以丢弃任何符号扩展位,这样该值就可以用作十六进制字符数组的索引

    // Masking sign extension.
    class HexByte {
      static public void main(String args[]) {
        char hex[] = {
          '0', '1', '2', '3', '4', '5', '6', '7',
          '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
        };
      byte b = (byte) 0xf1;
     System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
    }
    }
    

    以下是此文件的输出:

    b = 0xf1
    
  5. # 5 楼答案

    >>运算符是按位右移运算符

    简单的例子:

    int i = 4;
    System.out.println(i >> 1); // prints 2 - since shift right is equal to divide by 2
    System.out.println(i << 1); // prints 8 - since shift left is equal to multiply by 2
    

    负数的行为相同:

    int i = -4;
    System.out.println(i >> 1); // prints -2
    System.out.println(i << 1); // prints -8
    

    一般来说-i << k相当于i*(2^k),而i >> k相当于i/(2^k)

    在所有情况下(与任何其他算术运算符一样),都应确保不会溢出数据类型

  6. # 6 楼答案

    我相信是位移位运算符。如中所示,将所有1和0向右移动一个位置。(我想你可以想象,<;<;做了什么……:))