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
}
}
1 Replies - 384 Views - Last Post: 06 December 2012 - 09:28 AM
#1
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.
Replies To: Having problems figuring out 2's complement of a binary number
#2
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
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|