我写了补码转反玛的方法
public class Cat {
public static void main(String[] args) {
String str = "10011101";//补码
String complment = getComplment(str);//反玛
String original = getOriginalFromComplment(complment);//原玛
System.out.println(str + "--->" + original);
}
private static String getOriginalFromComplment(String str) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < str.length(); i++){
sb.append(str.charAt(i) == '0'? "1": "0");
}
return sb.toString();
}
private static String getComplment(String str) {
String complement = null;
if(str.charAt(str.length()-1) == '1'){
StringBuilder sb = new StringBuilder();
sb.append(str.substring(0, str.length()-1));
sb.append("0");
complement = sb.toString();
}else{
char[] ary = str.toCharArray();
for(int i = ary.length; i > 0; i--){
if(ary[i-1] == '1'){
ary[i-1] = '0';
break;
}else{
ary[i-1] = '1';
}
}
complement = new String(ary);
}
return complement;
}
}
-------------
10011101--->01100011
倒数减一