# Having problems figuring out 2's complement of a binary number

Page 1 of 1

## 1 Replies - 2700 Views - Last Post: 06 December 2012 - 09:28 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=302983&amp;s=f91c29bb8c2a564f0db225ba054f2e74&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 abbey21

Reputation: 0
• Posts: 18
• Joined: 05-December 12

# Having problems figuring out 2's complement of a binary number

Posted 06 December 2012 - 09:13 AM

So the code below will compute/print the 1's complement of the given binary number. I am now trying to compute/print the 2's complement of that binary number...I know 2's complement should be 1000101. Does anyone have any suggestions to alter this program to get the 2's complement? Thank you.

```public class Complement{
public static void main(String [] args){
String comp1="10101110";//some input string

char[] array;// some array of chars

String tmp = new String();//tmp = temporary string
tmp=comp1;//give tha value of comp1 to tmp
array=tmp.toCharArray();// fill the array with the chars of the tmp string
for(int i=0; i<comp1.length();i++)// loop through the array
{
if(array[i]=='1')//if the char at that poistion is 1
{
array[i]='0';	//make it 0
}
else array[i]='1';	//if not make it 1

}//end the for loop
comp1 = new String(array);//make the array string

System.out.println("The 1's complement of 10101110 is: ");
System.out.println(comp1);//print the complement of the new string
}
}

```

Is This A Good Question/Topic? 0

## Replies To: Having problems figuring out 2's complement of a binary number

### #2 g00se

• D.I.C Lover

Reputation: 3515
• Posts: 15,907
• Joined: 20-September 08

## Re: Having problems figuring out 2's complement of a binary number

Posted 06 December 2012 - 09:28 AM

You can't treat it as a String to do 2's complement as it involves addition to the number