Reputation: 1147
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);
}
}
Upvotes: 1
Views: 107
Reputation: 1625
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
Upvotes: 5