aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes shift operators for negative values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "shift operators for negative values" Watch "shift operators for negative values" New topic
Author

shift operators for negative values

Rosie Nelson
Ranch Hand

Joined: Nov 06, 2001
Posts: 31
JLS (15.19 Shift Operators) states:-
The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is (n/2^s). For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

Question:-
If I want to compute for a negative value of n, i.e -8 >> s what is the procedure... is there a formula that holds true for negative values?
e.g how would I calculate:-
(1) -8 >> 31
(2) -8 >> -3
Andre Zhang
Greenhorn

Joined: Aug 14, 2001
Posts: 9
Now matter what s is, it will mod 32 first (s%=32) if the type of n is int & mod 64 (s%=64) if the type of n is long.
Neha Sawant
Ranch Hand

Joined: Oct 11, 2001
Posts: 204
this is really confusing
i tried doing this
2<<3;
2<<-3;
both give different ans.
How do you shift nos having negative sign on right hand side.
Someone please help
Reagrds
neha


nss
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
OK the first thing to point out is that:
if the left-hand side is an int then the right-hand side is ANDed with 0x1F and if the left-hand side is a long then the right-hand side is ANDed with 0x3F.
Now, let's take a look at 2<<3 and 2<<-3.
2<<3 : No suprises here the result is 16 as expected.
BUT for 2<<-3 the story is different.
the right-hand side (-3) in binary is
11111111 11111111 11111111 11111101
and ANDed with 0x1F it gives
11101 which is in fact 29 (32-3) and the result of the shifting is 1073741824.
To summarize: the right-hand side is in all cases ANDed with 0x1F (or 0x3F) and that result is the one used in the shifting operation. So there is no way to shift more than 31 positions (to the left or to the right) because of that AND operation whatever the sign of the rigth-hand side is.
HIH

------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Neha Sawant
Ranch Hand

Joined: Oct 11, 2001
Posts: 204
Great ,i was not at all aware of this nor did it ever strike me.
thanks Rosie for removing this topic and
Thanks to Valentin for the great explanation
Regards
neha
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: shift operators for negative values