Search code examples
javaexceptionvalidatelongrange

NumberFormatException while converting Hexadecimal String to Long


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?


Solution

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

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

    produces

    -3742491290344848383