Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二进制到十进制转换器返回错误_Java_Constructor_Binary_Decimal_Converter - Fatal编程技术网

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呢