Exception hex to int number format in java

Trying to do this throws a numeric exception

int temp = Integer.parseInt("C050005C",16);

      

if I decrease one of the digits of the hex number it converts, but not otherwise. why and how to solve this problem?

+2


source to share


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


C050005C is 3226468444 decimal, which is more than Integer.MAX_VALUE . It won't match int

.



+5


source


Use this:

long temp = Long.parseLong("C050005C",16);

+4


source


The signed int type ranges from 0x7FFFFFFF to -0x80000000.

+2


source







All Articles