2

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),is(0xFFFF4C6A));

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You've exceeded the range of an integer.

Integer.MAX_VALUE = 2147483647
0xFFFF4C6A = 4294921322

Parsing it as a Long works:

Long.parseLong("FFFF4C6A",16)

1 Comment

perhaps 16 instead of Character.MAX_RADIX expresses the OP's intention better
2

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

Comments

1

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()

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.