File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes shift operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "shift operators" Watch "shift operators" New topic

shift operators

khella smith
Ranch Hand

Joined: May 06, 2002
Posts: 39
is the <<(left shift)signed or unsigned? i was doing some revision in javacaps and it said that the left shift is signed and in R&H it does not specify and i assumed it was signed.could it be considered unsigned because it inserts zeroes in new positions like the >>>(un-signed right shift)?
pls tell me
khella smith
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
There is no difference between a signed and an unsigned left shift, that's why there is only one left shift operator.
In 8-bit terms: take a low(ish), positive number to start with
64 << 1 = 01000000 << 1 = 10000000 = 128
So that's how normal unsigned left shifts work. Now consider an unsigned, large number:
192 << 1 = 11000000 << 1 = 10000000 = 384 % 256 = 128 (Overflow)
It still worked, even though the result did no longer fit inside an 8-bit number. The same bit pattern in signed guise:
-64 << 1 = 11000000 << 1 = 10000000 = -128
This is exactly the right result.
So you can see that left-shift works by shifting in zeroes from the right, on both signed and unsigned numbers.
- Peter
I agree. Here's the link:
subject: shift operators
It's not a secret anymore!