Reputation: 550
Given:A binary number in the form of String.Convert this into its 2's complement form
Example:
Input:
00000101
Output:
11111011
I know how to convert a binary number into its 1's compliment form. But I am unable to convert into 2 complement form.
For Example:
GivenString :111
1s Compliment 000
How to code1: Adding '1' to the 1's complement and 1+1=1?
MyCodeFor 1s Compliment:
public static String complimentDecimal(String strnew)
{
//Replace the 0s with 1s and 1s with 0s
StringBuilder sb = new StringBuilder();
for(int j=0;j<strnew.length();j++)
{
if(strnew.charAt(j)=='0')
sb.append("1");
else if(strnew.charAt(j)=='1')
sb.append("0");
}
String s1 = sb.toString();
}
Upvotes: 1
Views: 436
Reputation: 368
Convert the one's compliment to decimal form using Integer.parseInt(<String value>, 2)
You will get decimal form of the binary number. Add one to it and convert the number back to binary.
public static String complimentDecimal(String strnew)
{
int s2=Integer.parseInt(strnew,2);
if (s2==0)
{
String s4="1";
for(int j=0;j<strnew.length();j++)
{
s4+="0";
}
return s4;
}
else{
StringBuilder sb = new StringBuilder();
for(int j=0;j<strnew.length();j++)
{
if(strnew.charAt(j)=='0')
sb.append("1");
else if(strnew.charAt(j)=='1')
sb.append("0");
}
String s1 = sb.toString();
int s = Integer.parseInt(s1, 2);//parse int radix = 2 for binary
s++; //increment by one
return Integer.toBinaryString(s);
}
}
This will work for zero's.
Upvotes: 2