Unexpected NumberFormatException while parsing a hex string to an int value

后端 未结 5 1421
小鲜肉
小鲜肉 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

    You've exceeded the range of an integer.

    Integer.MAX_VALUE = 2147483647
    0xFFFF4C6A = 4294921322
    

    Parsing it as a Long works:

    Long.parseLong("FFFF4C6A",16)
    
    0 讨论(0)
  • 2021-01-26 02:55

    Your number represents a number greater than that assignable to an int. Try:

    Long.parseLong("FFFF4C6A", 16);
    

    which gives 4294921322.

    From the doc:

    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, …
    • The value represented by the string is not a value of type int.

    and it's the 4th case that you're hitting.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-26 03:03

    I don't know the assertThat() method, but your hexadecimal number "FFFF4C6A" is to big for an integer.

    For example, if you write :

    int number = Integer.parseInt("FFFF4C6A",16)

    you'll get the same error. A correct way to write the code would be :

    double number = Integer.parseInt("FFFF4C6A",16)

    0 讨论(0)
  • 2021-01-26 03:05

    If you just want to represent that hex string as an integer (since it is 32 bits), you need to use BigInteger:

    new BigInteger("FFFF4C6A", 16).intValue()
    
    0 讨论(0)
提交回复
热议问题