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

Community
  • 1
  • 1
Lonzak
  • 9,334
  • 5
  • 57
  • 88

3 Answers3

2

-2115381772 as hex does not fit in an Integer.

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

bidifx
  • 1,640
  • 13
  • 19
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.

nullptr
  • 3,320
  • 7
  • 35
  • 68
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.

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • Don't understand it fully. -2115381772 < -2147483648 thus a perfectly valid int. However Meraman explained it... – Lonzak Oct 15 '13 at 10:33
  • Well you provided the value ``-2115381772`` in hex and that's ``-142089918322`` decimal which is certainly smaller than ``-2147483648`` (and btw. ``-2115381772 > -2147483648``). – steffen Oct 15 '13 at 11:58