转换具有非常大数字的十六进制值的字符串

Convert a string with hex value of a very big number

我正在尝试将字符串 9C72E0FA11C2E6A8 转换为十进制值:

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

我希望得到值 11273320181906204328,但我得到了

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)

如何在 Java 中将十六进制转换为十进制?

谢谢!

使用 BigInteger 将字符串值作为参数传递并将基数作为参数

String strHexNumber = "9C72E0FA11C2E6A8";
BigInteger mySuperBigInteger = new BigInteger(strHexNumber , 16);

来自 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).

对于你的情况,你可以这样做:

BigInteger bigInt = new BigInteger(strHexNumber, 16);