简体   繁体   中英

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.

Because:

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

Code Throwing the 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 ?

Use BigInteger to avoid numeric limits of primitive int and 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.

Demo.

If your input value can be arbitrarily large, then @dasblinkenlight's answer involving BigInteger is your best bet.

However, if your value is less than 2 63 , then you can just use Long instead of Integer :

String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex);                             // 2540be3ff

Live demo .

Use Integer.parseUnsignedInt

When the number is above 2^31 but below 2^32, thus in the negative int range, you can do:

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.

Try this way:

 String largeNumberAsAString = "9999999999";
    System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue())); 

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