Java 二进制到十进制转换器返回错误
修理和整理转换器时,我注意到它以某种方式给出了不正确的转换 例如,当使用Java 二进制到十进制转换器返回错误,java,constructor,binary,decimal,converter,Java,Constructor,Binary,Decimal,Converter,修理和整理转换器时,我注意到它以某种方式给出了不正确的转换 例如,当使用BinaryNumber bn1=newbinarynumber(“1011”)创建要转换的新数字时
BinaryNumber bn1=newbinarynumber(“1011”)创建要转换的新数字时然后要求它用System.out.println(bn1.convertToDecimal())给出一个结果代码>它打印出3,而不是正确的结果11
我几乎可以肯定,我的实际转换是错误的,但在我的脑海中,我找不到错误
public class BinaryNumber {
private String n;
public BinaryNumber(String pn) {
n = pn;
}
public String getN() {
return n;
}
// Creating the .convertToDecimal()
public int convertToDecimal() {
int bitPosition = 0;
int sum = 0;
for (int i = n.length() - 1; i >= 0; i--) {
sum = sum + (int) Math.pow(2, bitPosition) * (n.charAt(i) - 48);
}
return sum;
}
// Creating the .add to add the two different binary numbers after
// converting
public int add(BinaryNumber bn2) {
return convertToDecimal() + bn2.convertToDecimal();
}
// Creating the .sub to subtract the two different binary numbers after
// converting
public int sub(BinaryNumber bn2) {
return convertToDecimal() - bn2.convertToDecimal();
}
}
您只需要增加bitposition变量
int位位置=0;
整数和=0
for (int i = n.length() - 1; i >= 0; i--) {
sum = sum + (int) Math.pow(2, bitPosition++) * (n.charAt(i) - 48);
}
return sum;
首先,Java有一个内置的二进制系统,使用原语int
类型。您可以通过将0b
放在二进制形式的数字之前来使用它
如果您这样做是为了学习,那么下面是发生的情况:
在每次迭代中,bitPosition
的值总是0
,因为您从不更新它。当然,您希望随着每次迭代增加它。这可以简单地通过改变
Math.pow(2位位置)
到
Math.pow(2,bitPosition++)
在变量被引用后使用++
来更改它。您还没有增加位位置,为什么不使用Integer.toBinaryString(int)
和Integer.parseInt(int,2)
?返回一个int
。为什么不使用1呢