wood burning stoves 2.0*
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
Author

Stupid Question asked better...

Milan Gupta
Greenhorn

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:
-2147483648
And a toBinaryString(i) will give you:
10000000000000000000000000000000
I buy this...
then if you do this shift operation on same i:
i >>= 31
a System.out.println(i) will give you:
-1
And a toBinaryString(i) will give you:
11111111111111111111111111111111
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:
10000000000000000000000000000001
I think I am missing something.
Milan
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.
HTH
Layne


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: http://aspose.com/file-tools
 
subject: Stupid Question asked better...