如果以 String
表示的数字高于 2,147,483,647,我有这行 Java 代码,它将抛出 NumberFormatException。
因为:
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
抛出 NumberFormatException 的代码:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
如何使用 String
参数而不是 int
参数获得与 Integer.toHexString()
相同的功能,因为 NumberFormatException
?
最佳答案
使用BigInteger
避免原始 int
和 long
的数字限制:
BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16); // Radix 16 indicates hex
System.out.println(x16);
该类方便地公开了一个采用String
的构造函数,该字符串被解释为数字的十进制表示形式。
关于Java : Need to get the same functionality of the Integer. toHexString() 由于 NumberFormat 异常,带有 String 参数而不是 Int 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47656946/