Skip to content

Something wrong with BigInteger

public static BigInteger OtherToDecimal(String value, int base) {
    BigInteger sum = new BigInteger("0");
    String kt = "0123456789ABCDEF";//
    for (int i = 0; i < value.length(); i++) {
        BigInteger k = BigDecimal.valueOf(pow(base, value.length() - 1 - i)).toBigInteger();
        sum = sum.add((BigInteger.valueOf(kt.indexOf(value.charAt(i))).multiply(k)));
    return sum;

when i test this function with base16 :F0F0F0F0F0F0F0, it return right result = 67818912035696880 BUT when i test with base16: F0F0F0F0F0F0F0F0, it returns wrong result: 17361641481138401580 which right result must be 17361641481138401520 please help me!


Math.pow delivers a double, 8 bytes. So from some huge double value, it becomes imprecise in the less significant digits.

You could have used

new BigInteger(value, base)

The repair is:

    BigInteger k = BigDecimal.valueOf(base).pow(value.length() - 1 - i));