Skip to content

Is this a valid Hex value?

I’m reading a series of Hex values, reading the value `0x03B6 using the code :

Integer.parseInt("0x03B6",16);

results in exception :

Exception in thread "main" java.lang.NumberFormatException: For input string: "0x03B6"

If however I remove the 0x at beginning of value the result is converted to HEX correctly :

Integer.parseInt("03B6",16)

Is 0X a convention to indicate it’s a hex value ? 03B6 is valid Hex ?

Using a Hex calculator – https://www.calculator.net/hex-calculator.html also does not recognize 0x03B6 but does recognize 03B6

Answer

Normally, they are interpreted at compile time. You need to use Integer.decode. If you omit the 0x prefix then you must specify a radix and use parseInt.

To decode using those strings in realtime, do the following.

String[] vals = { "0xF", "#111", "0x17C" };
for (String v : vals) {
    System.out.println(v + " -> " + Integer.decode(v));
}

prints

0xF -> 15
#111 -> 273
0x17C -> 380

Also, note that numbers prefixed with just a 0 will decode as octal.