LocalMagic
LocalMagic

Reputation: 117

Java binary shift operations

I found this java question on the internet and had some questions about it.

Which statements are accurate:

I'm a little unsure what a signed shift is, does it mean that it retains the sign of the binary number regardless of what happens in the shift itself (which would make the most sense to me) or does it mean that the MSB does not change unless it is overwritten in the shift operation itself.

so

Upvotes: 1

Views: 666

Answers (5)

theDazzler
theDazzler

Reputation: 1059

">>" performs a signed shift which fills in the new bits with whatever the leftmost bit is. The leftmost bit determines if the number is negative or positive. 0 for positive and 1 for negative. For example,

>> 1
10111100 becomes 11011110
the leftmost bit is a 1, so the new bits after the shift become ones

>> 1
01110011 becomes 00111001 since the leftmost bit is a 0

">>>" performs an unsigned shift which means the new bits are always filled with zeroes after the shift. For example,

>>> 1
10111100 becomes 01011110
the new bits are filled in as zeroes no matter what the leftmost bit is


enter code here

Upvotes: 1

Dave
Dave

Reputation: 14198

Another description: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

From the article: "The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension."

Upvotes: 2

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

<<  Signed left shift      op1 << op2 
>>  Signed right sift      op1 >> op2 
>>> Unsigned right shift   op1 >>> op2 

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

does it mean that it retains the sign of the binary number regardless of what happens in the shift itself (which would make the most sense to me) or does it mean that the MSB does not change unless it is overwritten in the shift operation itself.

That's the same thing. ;)

Whereas >>> will always overwrite the MSB with a 0, and therefore unsigned

If you do -1 >>> 0 it will still be negative, but its basically right ;)

left shift is not signed or unsigned, is just a left shift and as you say it may or may not change the sign.

Upvotes: 0

Marc
Marc

Reputation: 1984

Look in Java Language Specification: http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.19

Upvotes: 0

Related Questions