Search code examples
javastringasciinumber-formatting

How to solve NumberFormatException in Java when trying to convert a very large number from String


I am trying to convert every character of a string to its ascii value and concatenate those values to int.

example:

input: "Z8IG4"

output:9056737152.

What I have done so far is this:

String m = "Z8IG4";
String nm = "";

for(int i=0; i<m.length(); i++){
  char c = m.charAt(i);
  int cm = (int) c;
  nm+=Integer.toString(cm);
}

int foo = Integer.parseInt(nm);
System.out.println(foo);

This doesn't work and I don't know what I am doing wrong here.

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "9056737152"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at HelloWorld.main(HelloWorld.java:22)

Solution

  • It' because max value supported by int is 2147483647 and your value is out of range.

    You can find max value with Integer.MAX_VALUE

    You can use BigInteger f = new BigInteger(nm); for this