aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Shift Operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Shift Operators" Watch "Shift Operators" New topic
Author

Shift Operators

niting Grover
Greenhorn

Joined: Nov 22, 2004
Posts: 1
Hi ,

Can someone plz explain how do the >> (right shift operator) shift operators work in case of negative numbers i.e. how do i get the decimal value from applying this operator on a negative number ?

For eg whats the result of a >>1 (int a = -128) ?
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
-128 in decimal is 11111111 11111111 11111111 10000000 in binary

a >> 1 shifts the bits of a one place to the right, filling the gap on the left with a copy of the original leftmost (sign) bit, giving us
-64 in decimal which is 11111111 11111111 11111111 11000000 in binary


Mike Gershman
SCJP 1.4, SCWCD in process
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
To convert a two's complement negative binary number to decimal, replace every 1 with a 0 and every 0 with a 1, then add 1 to the result. Convert that number to decimal and show it with a minus sign.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Shift Operators