[英]Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception
I have this line of Java code that will throw NumberFormatException if the number represented as a String
is above 2,147,483,647. 我有这行Java代码,如果以
String
表示的数字大于2,147,483,647,则将引发NumberFormatException。
Because: 因为:
The int data type is a 32-bit signed two's complement integer.
int数据类型是32位带符号的二进制补码整数。 It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
最小值为-2,147,483,648,最大值为2,147,483,647
Code Throwing the NumberFormatException: 代码引发NumberFormatException:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
How can I get the same functionality of the Integer.toHexString()
with a String
parameter and not an int
parameter due to NumberFormatException
? 由于
NumberFormatException
我如何通过String
参数而不是int
参数获得Integer.toHexString()
的相同功能?
Use BigInteger
to avoid numeric limits of primitive int
and long
: 使用
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);
The class conveniently exposes a constructor that takes a String
, which gets interpreted as a decimal representation of a number. 该类方便地公开采用
String
的构造函数,该构造函数被解释为数字的十进制表示形式。
If your input value can be arbitrarily large, then @dasblinkenlight's answer involving BigInteger
is your best bet. 如果您的输入值可以任意大,那么@dasblinkenlight涉及
BigInteger
的答案就是最好的选择。
However, if your value is less than 2 63 , then you can just use Long
instead of Integer
: 但是,如果您的值小于2 63 ,则可以使用
Long
代替Integer
:
String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex); // 2540be3ff
Use Integer.parseUnsignedInt 使用Integer.parseUnsignedInt
When the number is above 2^31 but below 2^32, thus in the negative int range, you can do: 当数字大于2 ^ 31但小于2 ^ 32,因此在负int范围内时,可以执行以下操作:
int n = Integer.parseUnsignedInt("CAFEBABE", 16);
(I used hexadecimal here, as it is easier to see that above we are just in that range.) (我在这里使用了十六进制,因为更容易看到上面的数值在该范围内。)
However 9_999_999_999 is above the unsigned int range too. 但是9_999_999_999也在unsigned int范围之上。
Try this way: 尝试这种方式:
String largeNumberAsAString = "9999999999";
System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.