Difference between >>> and >>

前端 未结 7 1110
情歌与酒
情歌与酒 2020-11-22 07:13

What is the difference between >>> and >> operators in Java?

7条回答
  •  臣服心动
    2020-11-22 08:00

    >>> is unsigned-shift; it'll insert 0. >> is signed, and will extend the sign bit.

    JLS 15.19 Shift Operators

    The shift operators include left shift <<, signed right shift >>, and unsigned right shift >>>.

    The value of n>>s is n right-shifted s bit positions with sign-extension.

    The value of n>>>s is n right-shifted s bit positions with zero-extension.

        System.out.println(Integer.toBinaryString(-1));
        // prints "11111111111111111111111111111111"
        System.out.println(Integer.toBinaryString(-1 >> 16));
        // prints "11111111111111111111111111111111"
        System.out.println(Integer.toBinaryString(-1 >>> 16));
        // prints "1111111111111111"
    

    To make things more clear adding positive counterpart

    System.out.println(Integer.toBinaryString(121));
    // prints "1111001"
    System.out.println(Integer.toBinaryString(121 >> 1));
    // prints "111100"
    System.out.println(Integer.toBinaryString(121 >>> 1));
    // prints "111100"
    

    Since it is positive both signed and unsigned shifts will add 0 to left most bit.

    Related questions

    • Right Shift to Perform Divide by 2 On -1
    • Is shifting bits faster than multiplying and dividing in Java? .NET?
    • what is c/c++ equivalent way of doing ‘>>>’ as in java (unsigned right shift)
    • Negative logical shift
    • Java’s >> versus >>> Operator?
    • What is the difference between the Java operators >> and >>>?
    • Difference between >>> and >> operators
    • What’s the reason high-level languages like C#/Java mask the bit shift count operand?
      • 1 >>> 32 == 1

提交回复
热议问题