File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# two's complement aritmetic

Arno Du Toit
Greenhorn

Joined: Aug 20, 2002
Posts: 1
Please can someone give me a clear and simple explanation on how to convert a positive binary number to a negative one. I have come alot of explanations where they say you have to invert the bits and then add one. I have tried to do this, but they do not eplain where you have to add the one. Please explain or point me to an explanation.
Here is an example. 5 in binary is 0101. Invert the bytes you get 1010 then if you add one and drop th e0 at the end you get 1011 which apparently is -5. If you take another number like which is 0110 and you invert it you get 1001, now where do you add the one?? I know the answer is 1010. And then my final question how would you convert a negative binary to a positive one?
Ranch Hand

Joined: Jun 26, 2002
Posts: 104
i found this explanation in one of the threads here ...
Proceed as follows to get the decimal equivalent of a -ve number:
say -8
1. Invert all the bits.
--> so 1111 1000 becomes 0000 0111.
2. Strip all the leading zeros and convert to decimal.
--> so 0000 0111 becomes 111 which is equivalent to 7.
3. Add 1 to the result and then put the negative sign.
--> 7+1 = 8 and finally it becomes -8.
so 1111 1000 = -8.
To convert a -ve decimal to a binary just do the reverse.
Taking the example of -8
1.Strip it off the -ve sign and subtract 1.
-->so -8 becomes 8 and then 7.
2. Convert the decimal to binary
-->7 is 0000 0111 in binary.
3.Invert the bits
-->Result is 1111 1000. (same as the start of this message)

hope this helps
zarina
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Silver Surfer
Welcome to the Java Ranch, we hope you�ll enjoy visiting as a regular however,
your name is not in keeping with our naming policy here at the ranch. Please change your display name to an appropriate name as shown in the policy.
Thanks again and we hope to see you around the ranch!!

Dave
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
You can also try the Javaranch tutorial on bit manipulation.
Please tell Galactus I said hi.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Here are some lessons on 2's complement arithmetic:
http://www.javaforstudents.co.uk/bitty.html
http://www.javaforstudents.co.uk/secondbit.html

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In

I agree. Here's the link: http://aspose.com/file-tools

subject: two's complement aritmetic