0

I wanted to convert integer values to hex strings. I quickly searched stackoverflow and did it the following way (as the accepted solution indicated - however didn't look careful enough):

Integer.valueOf(String.valueOf(n), 16);

However when trying to convert

 Integer.valueOf(String.valueOf(-2115381772), 16)

it throws an NumberFormatException. So out of curiosity - why is the NumberFormatException thrown?

(Afterwards I changed the code to Integer.toHexString(-2115381772) and everything is working as expected.)

0

3 Answers 3

2

Because,

Integer.valueOf(String.valueOf(-2115381772), 16) considers -2115381772 value in Hexadecimal (16) base, and that is outside of range for int value. So you are getting that exception.

Integer.toHexString(-2115381772) considers -2115381772 value in decimal base, and it is in range of int value.

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

Comments

2

-2115381772 as hex does not fit in an Integer.

Try Long.valueOf(String.valueOf(-2115381772), 16); instead.

Comments

1

The minimum value of int is -2147483648.

So when you give any values less than -80000000, NumberFormatException will be thrown.

Because Integer.valueOf(String.valueOf(-80000000), 16) gives -2147483648 as output, which is the minimum value of int.

2 Comments

Don't understand it fully. -2115381772 < -2147483648 thus a perfectly valid int. However Meraman explained it...
Well you provided the value -2115381772 in hex and that's -142089918322 decimal which is certainly smaller than -2147483648 (and btw. -2115381772 > -2147483648).

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.