简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM