Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed right shift operator on negative operands

Tags:

java

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

like image 229
xdevel2000 Avatar asked May 05 '26 01:05

xdevel2000


1 Answers

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.

like image 108
John Kugelman Avatar answered May 06 '26 14:05

John Kugelman