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 Register / Login

# Conversion of negetive number to binary, etc.

Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
I am really confused as to how we convert a negative number into binary/octal/hexadecimal format.
For binary, would the following steps be appropriate?
1. Remove the negative sign and calculate the binary equivalent.
2. Reverse the digits (1 for 0 and 0 for 1)
It'd be really helpful if someone could solve and explain an example in this context.
Thanks,
Saket
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Hi Saket
The steps are convert the no. into binary. Inverse the digits. Add 1 to the result. This is known as 2's complement.
Well actually there is a 1's complement as well in that we simply inverse the bits. So 2's complemet is actually 1's complement + 1. There is a simpler method of finding 2's complement. Let say the intial no. in binary is 0110010010100. Now the 2's complement would be 1001101101100. The way to do it is, simply inverse all the bit after the first least significant 1 bit(excluding this 1 bit). 2's complement is used is widely used because in this +0 and -0 are equal to each other unlike in 1's complement where they are different.
[ June 09, 2003: Message edited by: Anupam Sinha ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Yes, that would be correct.
In order to convert a negative number to octal or hex, I'd first convert it to binary, then find the negative 2's complement version, and, finally, convert that to hex, like this:
Step 1: Convert 17 to binary:
00010001
Step 2: Find the 2's complement of that value:
11101111
Step 3: Convert that to hex:
0xEF
I hope that helps,
Corey

SCJP Tipline, etc.
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
For converting between two's complement, the rules I use are this:
1. From positive to negative: invert the bits and add 1.
2. From negative to positive: Write out in binary. Start at the right side and keep everything you see until the first 1 you encounter. Write the 1, and then invert all the remaining bits.
11111110 // Start at right
???10 // first 1 encountered. Keep it
00000010 // Invert all remaining bits to the left.
-(value) = -2.
Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
Thanks a lot Anupam, Corey and Brian. This thread has been very helpful to overcome by basic doubts.
Saket

subject: Conversion of negetive number to binary, etc.