Bitwise shift operator in Java

In Java, -4 → 2 gives -1, but -5 → 2 gives -2. Can anyone explain why? Here is a sample code:

byte r=-5;
r>>=2;
System.out.println(r);

Also in this scenario, → and →> operators give the same answer. Can anyone explain this as well?

+4
source share
5 answers

You can take a look at the bits. Using two-component notation, bits for -4and -5, showing only the last 8 bits for brevity:

-4: 1111 1100      
-5: 1111 1011

Moving bits to the right 2 positions with a sign extension:

-4 >> 2: 1111 1111 (-1)
-5 >> 2: 1111 1110 (-2)

Usually you think you are >>>not using a sign extension, and this is true, but in this case:

r >>>= 2;

... r int - , byte, "".

byte r = -5;     // 1111 1100
r >>>= -2;       // promoted to int:   11111111 11111111 11111111 11111010
                 // bit shift:         00111111 11111111 11111111 11111110
                 // cast back to byte: 11111110 (-2)

JLS, 15.26.2, , :

E1 op = E2 E1 = (T) ((E1) op (E2)), T - E1, , E1 .

- byte.

, r -4.

, , , byte:

System.out.println(r >>> 2);

:

1073741822
+5

- , (-4 → 2 -1, -5 → 2 -2)?

-4- : 11111100. , 11111111 (, , , .. ). -1 .

-5 : 11111011. , 11111110 ( , - ). -2.

>> >>> . - ?

. >>> -4 , 00111111111111111111111111111111. byte, 24 , 1. >>> -5.

+2

-4 == 0xFC. (.. ) 2 , 0xFF, -1.

-5 == 0xFB. 2 , 0xFE, -2.

0

, . 5: 0... 0101 ( 0 , 0101 , :

0101 >> 0010
0010 >> 0001

0001 1

1... 1011 ( , 1) , 1011,

1011 >> 1101 (we carry the other 1's)
1101 >> 1110 (we carry the other 1's)

1... 1110 -2

0

Java .

-5 11111011 , 2 11111110, -2. , -4 11111100, , 2, 11111111, -1 .

>> >>> , >>> , . java - r int , , 8 . -5 11111111111111111111111111111011, 2 11111111111111111111111111111110, typecast 11111110, -2.

, :

byte r = -5;
System.out.println(r >> 2);
System.out.println(r >>> 2);
r>>>=2;
System.out.println(r);
0

All Articles