Unexpected NumberFormatException while parsing a hex string to an int value

后端 未结 5 1420
小鲜肉
小鲜肉 2021-01-26 02:22

I want to parse an String containing 8 hex-digits (4bytes) but i got an NumberFormatException. What is wrong here?

assertThat(Integer.parseInt(\"FFFF4C6A\",16),i         


        
5条回答
  •  情歌与酒
    2021-01-26 02:55

    That is because the Integer.parseInt("FFFF4C6A",16) provided exceeds Integer.MAX_VALUE which is defined as public static final int MAX_VALUE = 0x7fffffff;

    Now, as per the Javadoc for parseInt(...), you would hit a NumberFormatException in either of the following cases:

    An exception of type NumberFormatException is thrown if any of the following situations occurs:

    • The first argument is null or is a string of length zero.
    • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
    • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
    • The value represented by the string is not a value of type int.

    In your case, since the String value supplied exceeds Integer.MAX_VALUE, you're satisfying the 4th clause for NumberFormatException

    Possible Solution: In order to parse this, use Long.parseLong(...) where the MAX_VALUE is defined as `public static final long MAX_VALUE = 0x7fffffffffffffffL

提交回复
热议问题