Java中>>、>>>、<<

definition:

Shift right >>: Signed shift right. A positive number is shifted to the right and the high-order position is filled with 0, and a negative number is shifted to the right and the high-order position is filled with 1.

Shift Left <<: Signed shift left. Positive numbers are shifted to the left and the lower bits are filled with 0, and negative numbers are shifted to the left and the lower bits are filled with 1.

Unsigned right shift >>>: Whether it is a positive or negative number, the high-order bits are filled with 0.

 

Chestnut: The following is represented by 32 bits

2 in binary: 0000 0000 0000 0000 0000 0000 0000 0010

-2 in binary: 1111 1111 1111 1111 1111 1111 1111 1110

Get the negative binary representation of 2: 2's complement plus 1

  1111 1111 1111 1111 1111 1111 1111 1101

  plus 1

  1111 1111 1111 1111 1111 1111 1111 1110

 

<1、2>>>1 

        1) Remove the red numbers: 0000 0000 0000 0000 0000 0000 0000 001 0 

      2) High-order fill with 0        : 0 000 0000 0000 0000 0000 0000 0000 0001

<2、2>>1

        1) Remove the red numbers: 0000 0000 0000 0000 0000 0000 0000 001 0 

      2) High-order fill with 0        : 0 000 0000 0000 0000 0000 0000 0000 0001

<3、-2>>1

      1) Remove the red numbers: 1 111 1111 1111 1111 1111 1111 1111 111 0

      2) High-order complement 1: 1 111 1111 1111 1111 1111 1111 1111 1111

<4、2<<1

      1)  Remove the red numbers: 0 000 0000 0000 0000 0000 0000 0000 0010

      2) Low-order fill with 0: 0 000 0000 0000 0000 0000 0000 0000 010 0

<5、-2<<1

      1)  Remove the red numbers: 1 111 1111 1111 1111 1111 1111 1111 1110 

      2) Low-order complement 1: 1 111 1111 1111 1111 1111 1111 1111 110 1

<6、-2>>>1

      1)  Remove the red numbers: 1111 1111 1111 1111 1111 1111 1111 111 0

      2) High-order fill with 0: 0 111 1111 1111 1111 1111 1111 1111 1111

Summarize:

2>>>1 is equivalent to 2 multiplied by 2^1 Similarly 2>>>2^n is equivalent to multiplied by 2^n Unsigned bit operations are filled with 0

2>>1    is equivalent to multiplying 2 by 2^1. Similarly, 2>>>2^n is equivalent to multiplying by 2^n. The high order of positive numbers is filled with 0, and the high order of negative numbers is not 1.

2<<1    is equivalent to multiplying 2 by 2^1. Similarly, 2>>>2^n is equivalent to multiplying by 2^n. Positive numbers are shifted to the left and the lower bits are filled with 0, and negative numbers are shifted to the left and the lower bits are supplemented by 1.

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326081727&siteId=291194637