我正试图找到一种快速/简单的方法,将两个补码二进制字符串转换为一个负十进制数。我尝试过使用这个问题中提供的方法,但它不起作用。这是我试图运行的代码:
short res = (short)Integer.parseInt("1001", 2);
System.out.println(res);当我运行这段代码时,结果是9,是不是遗漏了什么?我做错什么了?
发布于 2016-05-05 21:48:25
在二补算法,之后,我写了以下内容:
public static int getTwosComplement(String binaryInt) {
//Check if the number is negative.
//We know it's negative if it starts with a 1
if (binaryInt.charAt(0) == '1') {
//Call our invert digits method
String invertedInt = invertDigits(binaryInt);
//Change this to decimal format.
int decimalValue = Integer.parseInt(invertedInt, 2);
//Add 1 to the curernt decimal and multiply it by -1
//because we know it's a negative number
decimalValue = (decimalValue + 1) * -1;
//return the final result
return decimalValue;
} else {
//Else we know it's a positive number, so just convert
//the number to decimal base.
return Integer.parseInt(binaryInt, 2);
}
}
public static String invertDigits(String binaryInt) {
String result = binaryInt;
result = result.replace("0", " "); //temp replace 0s
result = result.replace("1", "0"); //replace 1s with 0s
result = result.replace(" ", "1"); //put the 1s back in
return result;
}下面是一些示例运行:
跑: 2的补充数: 1000:-8 二补: 1001:-7 二补: 1010:-6 2的补码: 0000: 0 二补: 0001: 1 二补: 0111: 7
发布于 2016-05-05 19:25:40
当我运行这段代码时,结果是9。
它应该是的。
我是不是遗漏了什么?我做错什么了?
您的代码和您引用的答案之间的区别是输入中的位数。“2‘s补语”没有指定宽度就不能很好地定义。您复制的答案是16位二位的补充,因为Java short是16位宽的。如果您想要4位2的补充,那么就没有相应的Java数据类型,因此您将无法采取相同的快捷方式。
https://stackoverflow.com/questions/37058582
复制相似问题