I'm reading Java spec. and here is written:
The value of n >> s is n right-shifted s bit positions with sign-extension. The resulting value is floor(n / 2s). For non-negative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.
So if I have the following:
27 >> 3 // 00011011 >> 3 = 00000011 = 3 = 27/8
the result is 3; in fact 27/8 = 3.375 and thus 3 is that value truncated.
But the spec say nothing when left operand is negative.
So if I have the following:
-50 >> 2 // 11001110 >> 2 = 11110011 = -13 != -50/4
the result is -13; but -50/4 = -12.5 and thus -13 is not that value truncated.
So what's the rounding system Java use when the left operand is a negative value?
Maybe ceil(n / 2s)?
The resulting value is
floor(n / 2s).
Floor means round down: round towards negative infinity. This is not the same as truncation, i.e. removing the fractional part. Truncation would cause positive numbers to round down and negative numbers to round up.
The floor of -12.5 is -13.
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With