Hey guys, so I’m writing a code analyzer and I’ve reached a bottleneck with parsing Java numbers from the source code. It works fine for the usual int, double and float numbers expect when they are represented as either octal of hexadecimal.

The ‘parse’ method of Integer and Double don’t accept the convention of number representation in the Java language. For example 0xAB is a hexadecimal number in Java, however the Integer.parseInt(String s, int radix) method would require the format AB. Of course such conversion is rather trivial; however consider the hexadecimal number 0xDadaCafe, which is actually the int -623195394. This is because the hex number can’t be represented in 32-bits so it’s sorta round robin’d to be negative… well that’s what I think. The actual decimal value is 3671771902. The problem is the hex number causes a NumberFormatException error.

If anyone can suggest how to identify that this number will indeed give a negative answer or how to simply parse the hex as a negative number, could you please explain? The issue with identifying that the hex number is too large for int representation seems somewhat difficult… I’m not sure how to tackle that.

The next part of what I’d like to do is check for too large or too small numbers, i.e. determine if a number is within the correct primitive type’s range. I think I could do this:

if (tokenString.compareTo(“2147483647”) > 0)
	//number is too big

Would that work for all cases? Here the number 2147483647 is the largest int value and tokenString stores my number as a String which is extracted from the Java source file.
Any insight would be great! Thank you.

9 Years
Discussion Span
Last Post by PoovenM

Thanks guys :) I can't seem to get the mindprod link open though? It just displays a blank page.. anyway my lecture suggested I use the parse method from class Long to parse the Hex and Octal number and in that way I'll be able to avoid the formation of the negative number; should the 'long' integer be too big for the 'int' type then I'll know that that hex/octal number would generate a negative 'int' number.

As for my 'NumberFormatException,' my other lecture said that in my case, such an exception would only occur if the number is out of bounds (since other errors are picked up when the source code is tokenized). So my problem is solved :) Thank you guy for your help, I will look up the 'BigInteger' class!

Power to the ppl!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.