【发布时间】:2016-01-08 02:56:45
【问题描述】:
当我注意到转换器以某种方式给出了不正确的转换时,我正在修复和整理转换器。
例如,当使用BinaryNumber bn1 = new BinaryNumber("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();
}
}
【问题讨论】:
-
你没有增加你的位位置
-
为什么不使用
Integer.toBinaryString(int)和Integer.parseInt(int, 2)?你返回一个int。 -
为什么不使用
1 << bitPosition(左移运算符)?
标签: java constructor binary decimal converter