PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

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

 August 12, 2022     biginteger, decimal, hex, java     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing