0
Integer.parseInt("ff8ca87c", 16);

This gives me a NumberFormatException for some reason. Do you know why that is?

Exception in thread "main" java.lang.NumberFormatException: For input string: "ff8ca87c"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
3
  • @John3136 yes, it doesn't work either Commented Feb 8, 2012 at 9:34
  • @John3136 - The spec doesn't mention the 0x prefix at all. Commented Feb 8, 2012 at 9:34
  • You are probably right - 0x would actually be on an int v=0xabcd rather than in a string. Commented Feb 8, 2012 at 9:38

1 Answer 1

6

The reason it fails is that you're trying to put +0xff8ca87c into a signed integer. The maximum value of a 32-bit signed integer is +0x7fffffff, because the most significant bit is used to store the sign.

Try using a long instead. The maximum value of a 64-bit signed int is 0x7fffffffffffffff, which is more than adequate for your needs in this case.

Or, in Java 8 you can use Integer.parseUnsignedInt("ff8ca87c", 16); which will treat the value as an unsigned integer.

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

3 Comments

Thanks, I wasn't really thinking about that. I confused the signed and unsigned int bounds. Unfortunately I'll have to test if parsing to long, and converting back to int effects the values of the bits (pesky sign bit!)
Surprisingly no, the bits all stay consistent through the whole conversion, process. Useful!
You might find Guava's UnsignedInts.parseUnsignedInt relevant.

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.