Exception hex to int number format in java
4 answers
This will lead to an integer overflow as integers will always be signed in Java. From the documentation for this method (emphasis mine):
A type exception is
NumberFormatException
thrown when one of the following situations occurs:
- The first argument is null or a zero-length string.
- The radius is either less than Character.MIN_RADIX or greater than Character.MAX_RADIX.
- Any character in the string is not a digit of the specified radius, except that the first character can be a minus sign '-' ('\ u002D'), provided that the string is longer than length 1.
- The value represented by the string is not an int.
It will fit into an unsigned integer. But this is not the case in Java.
So your best bet here might be to use long
and then just put the lower 4 bytes of that long into an int:
long x = Long.parseLong("C050005C", 16);
int y = (int)(x & 0xffffffff);
You might even be able to mess up the "and" here, but I can't check right now. But that could cut it down to
int y = (int)Long.parseLong("C050005C", 16);
+10
source to share