Java.lang.NumberFormatException when converting Hex String to Int

I want to convert a hexadecimal string to a decimal, but I got an error in the following code:

String hexValue = "23e90b831b74"; int i = Integer.parseInt(hexValue, 16); 

Error:

 Exception in thread "main" java.lang.NumberFormatException: For input string: "23e90b831b74" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:495) 
+5
source share
2 answers

23e90b831b74 too large to fit int .

You can easily see that by counting numbers. Every two digits in a hexadecimal number require one byte, so 12 digits require 6 bytes, and int only 4 bytes.

Use Long.parseLong .

 String hexValue = "23e90b831b74"; long l = Long.parseLong(hexValue, 16); 
+13
source

This happens when "the string cannot be parsed as an integer." Among other reasons, this will occur if the value exceeds Integer.MAX_VALUE or Integer.MIN_VALUE.

The largest numerical parsing as int is 2147483647 (231-1), and the longest is 9223372036854775807 (263-1), only about two times. To parse arbitrarily long numbers, use BigInteger:

 import java.math.BigInteger; BigInteger number = new BigInteger(hexValue); 
+3
source

Source: https://habr.com/ru/post/1238081/


All Articles