thatJavaNerd thatJavaNerd - 5 months ago 20
Java Question

Parsing a Hexadecimal String to an Integer throws a NumberFormatException?

So, In Java, you know how you can declare integers like this:

int hex = 0x00ff00;


I thought that you should be able to reverse that process. I have this code:

Integer.valueOf(primary.getFullHex());


where primary is an object of a custom Color class. It's constructor takes an Integer for opacity (0-99) and a hex String (e.g.
00ff00
).

This is the
getFullHex
method:

public String getFullHex() {
return ("0x" + hex);
}


When I call this method it gives my this
NumberFormatException
:

java.lang.NumberFormatException: For input string: "0xff0000"


I can't understand what's going on. Can someone please explain?

Answer

Will this help?

Integer.parseInt("00ff00", 16)

16 means that you should interpret the string as 16-based (hexadecimal). By using 2 you can parse binary number, 8 stands for octal. 10 is default and parses decimal numbers.

In your case Integer.parseInt(primary.getFullHex(), 16) won't work due to 0x prefix prepended by getFullHex() - get rid of and you'll be fine.