tags:

views:

236

answers:

4

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?

+8  A: 

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. But that's no option in Java.

So 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);
Joey
+5  A: 

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

ChssPly76
+2  A: 

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

Frank Bollack
+3  A: 

Use this:

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

michael.kebe