Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes binary shift operations with negative RHS ? 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 "binary shift operations with negative RHS ?" Watch "binary shift operations with negative RHS ?" New topic
Author

binary shift operations with negative RHS ?

sivaram subram
Greenhorn

Joined: Apr 24, 2001
Posts: 9
hi javaranchers !
i am not able understand what's happening when RHS of the binary shift operands is negative ? (say 2 >> -2) . It does not give a compile error !
can anyone explain the logic behind the output of such operations?
thanks
sivaram
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Sivaram,
When the value is positive we can say that for integers the shift amount is:
range modulus 32
and for long:
range modulus 64.
When the value is negative we can say the following for integers:
(32 - range) modulus 32
and for long:
(64 - range) modulus 64.
Therefore, we can say that the following 2 statements are equivalent:
1 << -2;
1 << 30;
Regards,
Manfred.
sing
Ranch Hand

Joined: Nov 29, 2001
Posts: 121
Hi Manfred,
Can you give more examples or any references to this negative shifting?Thank You.

Regards
Steffy
sing
Ranch Hand

Joined: Nov 29, 2001
Posts: 121
Hi Manfred,
Can you give more examples or any references of this negative shifting? Thank You.
Regards,
Steffy
Originally posted by Manfred Leonhardt:
Hi Sivaram,
When the value is positive we can say that for integers the shift amount is:
range modulus 32
and for long:
range modulus 64.
When the value is negative we can say the following for integers:
(32 - range) modulus 32
and for long:
(64 - range) modulus 64.
Therefore, we can say that the following 2 statements are equivalent:
1 << -2;
1 << 30;
Regards,
Manfred.

Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6

Here a just a couple of threads that you can refer to.
http://www.javaranch.com/ubb/Forum1/HTML/001638.html http://www.javaranch.com/ubb/Forum33/HTML/002836.html
This site has a search facility that I suggest you try to use before posting a question.
Thanks,
Junilu

Junilu - [How to Ask Questions] [How to Answer Questions]
 
Don't get me started about those stupid light bulbs.
 
subject: binary shift operations with negative RHS ?