Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Stupid Question asked better...

Milan Gupta
Greenhorn
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
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
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)

Layne Lund
Ranch Hand
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

Phil Chuang
Ranch Hand
Posts: 251
Barry's absolutely right.
Look up "two's complement binary negative number"