简体   繁体   中英

How can -1 divided by 2 result in -1? (bitwise operation >>)

I was surprised to see that -1 divided by 2 using bitwise operations results -1.

I was expecting 0 to be returned.

Just like when you divide 1 or -1 by 2 the decimal part is removed and we get zero. This might have to do with Two's complement but is just a guess and a guess that I don't fully understand.

can somebody explain it?

-1 >> 1 = -1

-1 / 2 = 0

 public class JavaFiddle
  {
    public static void main(String[] args)
    {
      System.out.println(-1 >> 1);
      System.out.println(-1 / 2);
    }
  }

Negative number in java is representated using a notation called 2's complement . If we assume the size of the signed integer is 8. you can think of 2's complement like this

2 will be  00000010
1 will be  00000001
0 will be  00000000
-1 will be 11111111 (Count in reverse from max)
-2 will be 11111110
-3 will be 11111101

(Actually in java the size of int is 4 bytes)

>> this is signed bitwise right shift operator. according to the documentation it fills 0 on the leftmost position for positive numbers and for negative numbers it will fill the same position with 1.

Which means shifting -1 any number of time gives -1 only.

11111111 >> 1 = 11111111

This is because of the Non-equivalence of arithmetic right shift and division meaning for negative numbers division by 2 and right shift should not be considered equal in all cases

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM