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

Stupid Question asked better...

Milan Gupta

Joined: Aug 03, 2002
Posts: 7
Okay, let me ask this question a little better...
if you have:
int i=1;
and you do this shift operation:
i <<= 31;
a System.out.println(i) will give you:
And a toBinaryString(i) will give you:
I buy this...
then if you do this shift operation on same i:
i >>= 31
a System.out.println(i) will give you:
And a toBinaryString(i) will give you:
I don't buy this. I buy the binary representation but
the binary value of 11111111111111111111111111111111
should be -2147483647 decimal not -1 decimal
I thought -1 as binary would be:
I think I am missing something.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
To find the bit pattern for the negative of an integer you "flip the bits and add one".
Because I'm lazy I'll do it with 8 bits.
00000001 (8 bit pattern for 1)
11111110 (flip the bits)
11111111 (add one, to get the 8 bit pattern for -1)

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
The method you used to get the binary representation of negative one is called sign-magnitude. This is definitely a valid way to store numbers in binary. However, most modern computers store integer values in two's compliment form. Barry described how it works very well. If you are interested in more details, you can check out this threadon another message board.
I'm sure you can find tons of information if you google either "sign-magnitude" or "twos compliment." They are common enough topics in the computer world. You should also be able to find the pros and cons of each method. So far, the pros of twos compliment form have beat out those of sign-magnitued.

Java API Documentation
The Java Tutorial
Phil Chuang
Ranch Hand

Joined: Feb 15, 2003
Posts: 251
Barry's absolutely right.
Look up "two's complement binary negative number"
I agree. Here's the link:
subject: Stupid Question asked better...
It's not a secret anymore!