2

I am trying to convert the following Hexadecimal string cc10000000008401 to Long. Java unexpectedly generating NumberFormatException.

System.out.println(Long.parseLong("cc10000000008401",16));

I think, It should not generate exception as the long representation of the above hexadecimal string is "-3742491290344848383L" which is well inside the range of Long.

Could you please help me to know why I am getting NumberFormatException?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Tarun
  • 3,162
  • 3
  • 29
  • 45
  • Possible duplicate of [How to convert a hexadecimal string to long in java?](https://stackoverflow.com/questions/5153811/how-to-convert-a-hexadecimal-string-to-long-in-java) –  Aug 02 '18 at 12:52

2 Answers2

4

cc10000000008401 is 14,704,252,783,364,703,233 which is larger than Long.MAX_VALUE of 9,223,372,036,854,775,807.

Since it overflows long you need to use BigInteger to store it. Since your text values comes as hex you can parse it providing correct radix:

BigInteger i = new BigInteger("cc10000000008401", 16);
System.out.println(i); // 14704252783364703233
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Could you please tell how did you calculate its decimal value. I am getting following decimal value: ‭-3742491290344848383‬ – Tarun Aug 02 '18 at 12:57
  • I mean, How did you get this value "14,704,252,783,364,703,233". – Tarun Aug 02 '18 at 13:01
  • as he commented/answered, by `new BigInteger("...", 16)` (Note that `parseLong` expects a `-` sign for negative numbers) – user85421 Aug 02 '18 at 13:07
3

In Java8, Long.parseUnsignedLong (javadoc) will handle this.

System.out.println(Long.parseUnsignedLong("cc10000000008401",16));

produces

-3742491290344848383

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245