문제

This question already has an answer here:

I have written a function to convert string to integer

   if ( data != null )
   {
        int theValue = Integer.parseInt( data.trim(), 16 );
        return theValue;
   }
   else
       return null;

I have a string which is 6042076399 and it gave me errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "6042076399"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:461)

Is this not the correct way to convert string to integer?

도움이 되었습니까?

해결책

Here's the way I prefer to do it:

Edit (08/04/2015):

As noted in the comment below, this is actually better done like this:

String numStr = "123";
int num = Integer.parseInt(numStr);

다른 팁

An Integer can't hold that value. 6042076399 (413424640921 in decimal) is greater than 2147483647, the maximum an integer can hold.

Try using Long.parseLong.

That's the correct method, but your value is larger than the maximum size of an int.

The maximum size an int can hold is 231 - 1, or 2,147,483,647. Your value is 6,042,076,399. You should look at storing it as a long if you want a primitive type. The maximum value of a long is significantly larger - 263 - 1. Another option might be BigInteger.

That string is greater than Integer.MAX_VALUE. You can't parse something that is out of range of integers. (they go up to 2^31-1, I believe).

In addition to what the others answered, if you have a string of more than 8 hexadecimal digits (but up to 16 hexadecimal digits), you could convert it to a long using Long.parseLong() instead of to an int using Integer.parseInt().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top