Question

Background

Using Integer.parseInt(someIntString, radix) doesn't always work and might return NumberFormatException on some cases.

I've checked the API and it says that such an exception will be returned :

if string cannot be parsed as an integer value, or radix < Character.MIN_RADIX || radix > Character.MAX_RADIX.

Sample code that causes the exception:

System.out.println(Integer.parseInt("ff00ff00",16));

On java I get the same exception.

Since an integer holds 4 bytes, this should still work, but it doesn't.

Here's a proof that such a thing is possible:

final String input="ff00ff00";
int output=0;
for(int i=0;i<input.length();++i)
  {
  output<<=4;
  final char c=input.charAt(i);
  if(c>='a')
    output+=c-'a'+10;
  else output+=c-'0';
  }
System.out.println(output);
System.out.println(Integer.toHexString(output));

Note that I know of using the Color.parseColor() function (and it's probably very similar to the code I've written), but I want to handle any radix and not just hexadecimal.

I also know that using the parseInt supports negative values parsing, so that's why it probably causes the exception.

The question

Is there a built in function or a know algorithm for parsing a string to an integer using any radix ?

I assume of course that the integer variable can hold the value (using max of 4 bytes ) and that the sign of the number is irrelevant .

Was it helpful?

Solution

Ok, I think there is no built in solution for this question, but it's quite easy to solve it using about the same code I've written in the question:

public static int parseInt(final String input,final int radix)
  {
  int output=0;
  for(int i=0;i<input.length();++i)
    {
    output*=radix;
    final char c=input.charAt(i);
    if(c>='a')
      output+=c-'a'+10;
    else output+=c-'0';
    }
  return output;
  }

OTHER TIPS

The problem is that java does not support unsigned integers, since "ff00ff00" is larger than a positive int could be, java counts it as out of range. A simple solution is to use Long.parseLong(string, radix), ideally you would change the type of the affected variables to longs, but you could make it work with some tricky casting too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top