Difference between >>> and >>

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

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

7条回答
  •  半阙折子戏
    2020-11-22 07:48

    The logical right shift (v >>> n) returns a value in which the bits in v have been shifted to the right by n bit positions, and 0's are shifted in from the left side. Consider shifting 8-bit values, written in binary:

    01111111 >>> 2 = 00011111
    10000000 >>> 2 = 00100000
    

    If we interpret the bits as an unsigned nonnegative integer, the logical right shift has the effect of dividing the number by the corresponding power of 2. However, if the number is in two's-complement representation, logical right shift does not correctly divide negative numbers. For example, the second right shift above shifts 128 to 32 when the bits are interpreted as unsigned numbers. But it shifts -128 to 32 when, as is typical in Java, the bits are interpreted in two's complement.

    Therefore, if you are shifting in order to divide by a power of two, you want the arithmetic right shift (v >> n). It returns a value in which the bits in v have been shifted to the right by n bit positions, and copies of the leftmost bit of v are shifted in from the left side:

    01111111 >> 2 = 00011111
    10000000 >> 2 = 11100000
    

    When the bits are a number in two's-complement representation, arithmetic right shift has the effect of dividing by a power of two. This works because the leftmost bit is the sign bit. Dividing by a power of two must keep the sign the same.

提交回复
热议问题