I am trying to convert string 9C72E0FA11C2E6A8 to decimal value:
String strHexNumber = "9C72E0FA11C2E6A8";
Long decimalNumber = Long.parseLong(strHexNumber, 16);
System.out.println("Hexadecimal number converted to decimal number");
System.out.println("Decimal number is : " + decimalNumber);
I expected to get value 11273320181906204328
, but I got
Exception in thread "main" java.lang.NumberFormatException: For input string: "9C72E0FA11C2E6A8"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:592)
at ConvertHexToDecimalExample.main(ConvertHexToDecimalExample.java:22)
How can I convert hex to decimal in Java?
Thank you!
Use a BigInteger pass the String value as argument and give the radix as parameter
String strHexNumber = "9C72E0FA11C2E6A8";
BigInteger mySuperBigInteger = new BigInteger(strHexNumber , 16);
From Java API document for BigInteger :
public BigInteger(String val, int radix)
Translates the String representation of a BigInteger in the specified radix into a BigInteger. The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).
In your case, you can do like this :
BigInteger bigInt = new BigInteger(strHexNumber, 16);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With