Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string with hex value of a very big number

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!

like image 257
Arthur Avatar asked Jan 04 '23 17:01

Arthur


2 Answers

Use a BigInteger pass the String value as argument and give the radix as parameter

String strHexNumber = "9C72E0FA11C2E6A8";
BigInteger mySuperBigInteger = new BigInteger(strHexNumber , 16);
like image 194
ΦXocę 웃 Пepeúpa ツ Avatar answered Jan 24 '23 16:01

ΦXocę 웃 Пepeúpa ツ


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);
like image 26
Mickael Avatar answered Jan 24 '23 17:01

Mickael