BigInteger数学函数不返回预期值

时间:2015-12-23 13:43:39

标签: java math biginteger

我有BigInteger方法,它接受4个数字的string[]数组输入,将数字转换为int[],然后对其应用大量数学运算。

public BigInteger convert32Bit(String[] array)
{
    System.out.println("Array being converted is "+Arrays.toString(array)+"\n");
    int[] tempArray = new int[array.length];
    ArrayList<BigInteger> tempBigIntList = new ArrayList<BigInteger>();
    int i = 0;
    for(String s:array)
    {
        int power = 4-i;
        tempArray[i]= Integer.parseInt(s);
        String string = Integer.toString(tempArray[0]);
        BigInteger myBigInt = new BigInteger(string);
        BigInteger num2 = myBigInt.multiply(new BigInteger("256").pow(power));
        System.out.println(tempArray[i]+" is being multiplied by 256^"+power+" which equals "+num2);
        tempBigIntList.add(num2);
        i++;
    }

    BigInteger bigInt32Bit = new BigInteger("0");
    for(BigInteger bI:tempBigIntList)
    {
        bigInt32Bit.add(bI);
    }

    System.out.println("\nThe final value is "+bigInt32Bit);

    return bigInt32Bit;
}

但是有一个问题。如果我将数组"123", "0", "245", "23"作为输入。我得到以下输出。

Wrong output

我期待的输出是

Array being converted is [123, 0, 245, 23]

123 is being multiplied by 256^4 which equals 528280977408
0 is being multiplied by 256^3 which equals 0
245 is being multiplied by 256^2 which equals 16056320
23 is being multiplied by 256^1 which equals 5888

The final value is 528297039616

有人可以帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

替换此行

bigInt32Bit.add(bI);

bigInt32Bit = bigInt32Bit.add(bI);

您这样做是因为BigIntegerimmutable。这意味着您必须为bigInt32Bit创建新值,而不是仅调整旧值。另外(如@justhalf所述)替换行

String string = Integer.toString(tempArray[0]);

String string = Integer.toString(tempArray[i]);

以便在应用数学运算符时使用正确的值。

答案 1 :(得分:0)

BigInteger是不可变的,因此bigInt32Bit.add(bI);将导致你拥有第一个元素的价值。为了添加所有值,您可以执行以下操作:

 bigInt32Bit = bigInt32Bit.add(bI);//assign it

此外,您只是将数组的第一个元素作为String string = Integer.toString(tempArray[0]);等bigInteger的输入传递,它应该是String string = Integer.toString(tempArray[i]);。我不会使用数组,如果它没有在任何地方使用,而不是只使用整数变量。