Converting a 2's complement to the proper integer

• 10-10-2011, 12:58 AM
Chuklol
Converting a 2's complement to the proper integer
So my question accepts an input as an 8 char string that is a 2s complement of an integer, and then prints the right integer out. I cannot use any classes that do the conversion but i can use any I/O facilities.

Now i am still new to Java terms and not very knowledgeable of terms yet, so what does it mean that i can use any I/O facilities.

Back to what i am thinking of doing

I accept the string lets say, 000000C2 which is 194, (c = 12) 12 x 16^1 + 2*16(0) == 192 + 2 = 194

I send my string to
Code:

```public String toBinary (String s){             String ret = "";             while (s.length () != 0){                     if(s.charAt (0) == '0'){                             ret = ret + "0000";                     }```
Which will convert 0 - F to its 4 binary part. Then returns the 32 bit binary code.
Now if it positive i can just go through right to left if the value is 1 i add 16^i to an int, and i increases every time i loop through a value.
If negative i have to twos complement - convert 1s to 0s, 0s to 1s and i subtract one because im going from twos complement back to its original.
• 10-10-2011, 05:47 AM
jing-yi
Re: Converting a 2's complement to the proper integer
Try this,

System.out.println(Integer.parseInt("000000C2",16) );

Regards,
Jing-yi