我有一个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"
作为输入,则会得到以下输出。
我期望的输出是: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
能有人帮忙修复这个问题吗?
String string = Integer.toString(tempArray[0]);
应该改为tempArray[i]
。 - justhalfBigInteger
的不可变性存在困惑,我认为这个问题是相当好的。 - justhalf