BigInteger 数学函数不返回预期值

BigInteger mathematical functions not returning expected values

我有一个 BigInteger 方法,它采用 string[] 数组输入 4 个数字,将数字转换为 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" 作为输入。我得到以下输出。

我期望的输出是

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

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

替换此行

bigInt32Bit.add(bI);

bigInt32Bit = bigInt32Bit.add(bI);

你这样做是因为 BigIntegerimmutable. This means that you have to create a new value for bigInt32Bit instead of just adjusting an old one. Also (as @justhalf 说)替换行

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

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

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

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

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

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