Reputation: 21
Why do both unsigned right shift (logical right shift) and signed right shift (arithmetic right shift) produce the same result for negative numbers?
Log.v("-59 >>> 5 expected 6, actual", String.valueOf((byte)(-59 >>> 5)));
Log.v("11000101 >>> 5 expected 00000110, actual",Integer.toBinaryString( -59 >>> 5));
Log.v("11000101 >> 5 expected 00000110, actual",Integer.toBinaryString( -59 >> 5));
Android Studio Logcat output
-59 >>> 5 expected 6, actual: -2
11000101 >>> 5 expected 00000110, actual: 111111111111111111111111110
11000101 >> 5 expected 00000110, actual: 11111111111111111111111111111110
Upvotes: 0
Views: 167
Reputation: 28
Right shift operator:- if the number is negative then it fills with 1. if the number is positive then it fills with 0. Unsigned Shift operator:- It fills with 0 irrespective of sign of the number.
Upvotes: 0
Reputation: 4524
This is normal behavior. Any integer with a negative value has a binary representation starting with infinite 1s.
So if you start out with say: -3 the binary representation looks like this:
...11 1101
So if we right shift this by 2 we get
...11 1111
Now for the unsgined/signed right shift. This relies on the fact that we don't have infinite digits in our integer. So say we have an 8bit integer assigned as -3 it looks like this:
1111 1101
If we do a signed shift, it will look at the MSB (most significant bit, the most left one) and preserve the value of that when shifting. So a signed shift right by 3 looks like this:
1111 1111
On the contrary, a unsigned right shift will not check the MSB and just shift right and fill with zeroes resulting in this:
0011 1111
This is exactly what you're seeing but the output truncates the preceding zeroes away.
If you don't know why negative integers are stored that way, check this answer.
(b & 0xff) >>> 5
behaves differentlyIntegers in java are 32bit, that means the binary representation will have 32 digits. Your -59 will look like the following binary representation:
1111 1111 1111 1111 1111 1111 1100 0101 == -59
0000 0111 1111 1111 1111 1111 1111 1110 == -59 >>> 5
If you now and this together with 0xff
you get the following:
1111 1111 1111 1111 1111 1111 1100 0101 == -59
0000 0000 0000 0000 0000 0000 1111 1111 == 0xff
0000 0000 0000 0000 0000 0000 1100 0101 == -59 & 0xff
0000 0000 0000 0000 0000 0000 0000 0110 == (-59 & 0xff) >>> 5
Upvotes: 1