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.