Amit Yadav
Amit Yadav

Reputation: 35044

Java Bitwise shift operator with Negative Operands

Operand1 ShiftOperator Operand2

Shift Rule

Right shift 
81814621>>-12 = 78
81814621>>>-12 = 78 

OK!!



Right shift (Operand1 is NEGATIVE)
-81814621>>-12 = -79
-81814621>>>-12 = 4017

Why different?
Left shift 
21<<-12 = 22020096
-21<<-12 = -22020096 
Unlike Right shift no matter Operand1 is Positive/Negative  
only sign get changed instead value

Thanks for all of your support! now i have a better idea on it...:)

Upvotes: 1

Views: 1202

Answers (2)

user207421
user207421

Reputation: 310860

Wherever you got that from, it's wrong. Operand2 cannot possibly be either negative or have anything at all in its leftmost five bits after masking it with 0x1F. There is nothing in the Java Language Specification about taking the twos-complement of the shift distance, or using its left-most five bits. Read what it really says. Don't rely on arbitrary sources, or just make it up.

EDIT -81814621 is 0xFFFFFFFFFB1F9BA3, -12 is 0xFFFFFFFFFFFFFFF4, bottom five bits of that is 0x14 or 20, right shift the first operand by 20 gives 0xFFFFFFFFFFFFFFB1, which is -79.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The "rule" about what to do with the right-hand side operator of the shift is there because the list of values of the right operand that truly make sense is very short: for ints the range is from zero to 31, inclusive; for longs, it is zero to 63.

All other values of int on the right-hand side need to be converted to a value in the specified range. The "rule" spells out the process - i.e. re-interpreting the number as positive (that's what the two's complement is about), then masking off the higher bits, keeping the last five.

In contrast, the left operand can retain its full range. The only difference that you are experiencing has to do with the difference between >> and >>>, that is, between an operator that interprets the left-hand side operand as signed for shifting, and the one that interprets it as unsigned.

The purpose behind the >>> operator is explained in this answer. In your example, when you right-shift a negative number with the two operators, the >> leaves the number negative by sigh-extending it (i.e. shifting ones on the left) while >>> makes it positive by shifting in zeros.

Upvotes: 2

Related Questions