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 REST with Spring (video course) this week in the Spring forum!

how to convert negative Integers to Binary format?

Greenhorn

Joined: Jun 17, 2003
Posts: 9
Can anyone please send me some link or explain how to convert negative integers to Binary format? Thanks.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
It isn't really that hard. We use two's compliment to represent negative numbers. That means that to figure out what a negative number would look like in binary, you start with the positive number.
Representing positive numbers in binary is simple. Binary is just like decimal in that each position to the left is a multiple of the number to its right. In decimal for example, each position is 10 times greater that the position to the right of it. We can show this with a simple diagram:
100,000 - 10,000 - 1,000 - 100 - 10 - 1
In a four digit number, the first position on the right is the ones place. The second position on the right is 10 times greater and is the tens place. The next position is 10 times greater and is the hundreds place and so on.
In binary, each position is 2 times bigger than the position to its right:
128 - 64 - 32 - 16 - 8 - 4 - 2 - 1
To represent a decimal number in binary, find the largest number in the diagram not larger than the number you want. So if we wanted to convert 81 to binary, we would start with 64. The 128 place gets a zero and the 64 place gets a 1.
01.. ....
We still have 81-64=17 left. The next largest number would be 16 so that slot gets a 1 while the 32 slot which was too big gets a zero.
0101 ....
We have only 17-16=1 left so all the places other than the one slot get a zero and the one slot gets a 1. So our final result is:
0101 0001
That's 81 in binary but we want negative 81. Now we apply two's compliment. Two's compliments has two parts:
1) reverse all the digits (change the 1's to 0's and the 0's to 1's)
2) add 1 to the result
So first reverse all the digits:
1010 1110
That was easy. Now we add one:
1010 1110
0000 0001
---------
1010 1111
And that is the answer. That is what -81 looks like in binary. We know it is negative because the sign bit (the first bit) is a 1.
To get the positive version of a negative number, apply the two's compliment rule again:
First reverse the digits:
0101 0000
0101 0000
0000 0001
---------
0101 0001
And we get 81 again!
[ July 16, 2003: Message edited by: Thomas Paul ]

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

And if you just wanted to see it without all the footwork, try Integer.toBinaryString().