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 Now add 1: 0101 0000 0000 0001 --------- 0101 0001 And we get 81 again! [ July 16, 2003: Message edited by: Thomas Paul ]

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

Nad Shez
Greenhorn

Joined: Jun 17, 2003
Posts: 9

posted

0

Thanks for the detailed explanation Thomas. I've got it! As for the footwork Steve, only if they'd allow a calculator in the exam, i wouldn't even need Integer.toBinaryString()!

I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com

subject: how to convert negative Integers to Binary format?