如何将补码数转换成2补码?

给定:String的forms的二进制数。将其转换为2的补码forms

例:

输入:

00000101

输出:

11111011

我知道如何将二进制数转换为1的恭维forms。 但我无法转换为2补充forms。

例如:

GivenString:111

1s赞美000

如何编码1:在1的补码和1 + 1 = 1中加“1”?

MyCodeFor 1s赞美:

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(); } 

使用Integer.parseInt(, 2)将一个恭维转换为十进制forms
您将获得二进制数的十进制forms。 添加一个并将数字转换回二进制。

 public static String complimentDecimal(String strnew) { int s2=Integer.parseInt(strnew,2); if (s2==0) { String s4="1"; for(int j=0;j 

这将适用于零。