Friday, August 12, 2022

[FIXED] Why does this BigInteger display incorrect results when entering FFFFFFFF (8 F)

Issue

I wanna use this code to achieve hexadecimal to decimal. When I enter FFFFFFFF(8F), it display 2415919102.However, 4294967295 is correct. And when I enter F or F or FFF...FFFFFFF(7F), it performs well.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String t = in.next();
    in.close();

    BigInteger bi = new BigInteger("0");
    int j = 0;
    for(int i=t.length()-1;i>=0;i--,j++) {
        char c = t.charAt(i);
        double val = Integer.valueOf(c+"",16);
        val = val*Math.pow(16, j);
        BigInteger bi2 = new BigInteger((int)val+"");
        bi = bi.add(bi2);           
    }
    System.out.println(bi.toString());
}

Solution

As Savior said in a comment:

    BigInteger bi = new BigInteger(t, 16);

4294967295

What went wrong?

You’re overflowing an int in this line:

        BigInteger bi2 = new BigInteger((int)val+"");

When processing the leading F in an 8 digit hex number, your double is 4.02653184E9 or 4026531840.0, but is converted to the largest possible int value, which is only 2147483647. So your code works for strings that fit in int, up to 7FFFFFFF, but gives incorrect results beyond that.



Answered By - Ole V.V.
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.