xdevel2000
xdevel2000

Reputation: 21364

Signed right shift operator on negative operands

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)?

Upvotes: 3

Views: 117

Answers (2)

John Kugelman
John Kugelman

Reputation: 361565

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.

Upvotes: 8

Zefick
Zefick

Reputation: 2119

Generally speaking Java does not use a rounding system at all, it just shifts some bits. If you need floor or ceil then use floor or ceil and use bit-shift operators when you need them.

Upvotes: 1

Related Questions