1 Replies - 1116 Views - Last Post: 06 December 2012 - 09:28 AM Rate Topic: -----

#1 abbey21  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2553
  • View blog
  • Posts: 10,641
  • 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
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1