Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex to int number format exception in java

Tags:

java

I am getting a number format exception when trying to do it

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

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

like image 612
anon Avatar asked Oct 21 '09 07:10

anon


2 Answers

This would cause an integer overflow, as integers are always signed in Java. From the documentation of that method (emphasis mine):

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
  • The value represented by the string is not a value of type int.

It would fit into an unsigned integer, though. As of Java 8 there's Integer.parseUnsignedInt (thanks, Andreas):

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

On earlier Java versions your best bet here might to use a 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);

Maybe you can even drop the bitwise "and" here, but I can't test right now. But that could shorten it to

int y = (int) Long.parseLong("C050005C", 16);
like image 57
Joey Avatar answered Sep 29 '22 02:09

Joey


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

like image 36
ChssPly76 Avatar answered Sep 29 '22 01:09

ChssPly76