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?
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.
Integer.valueOf(string) assumes a decimal representation. You have to specify that the number is in hex format, e.g.
int value = Integer.valueOf("00ff0000", 16);
Note that Integer.valueOf(string,16); does not accept a prefix of 0x
. If your string contains the 0x
prefix, you can use Integer.decode("0x00ff0000");
Try to use decode method:
Integer.decode("0x00ff00");
DecodableString:
- Signopt DecimalNumeral
- Signopt 0x HexDigits
- Signopt 0X HexDigits
- Signopt # HexDigits
- Signopt 0 OctalDigits
You can read about it here https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#decode(java.lang.String)
The parseInt method only accepts the number part, not any kind of "base" indicator such as "0x" for hexadecimal or "0" for octal. Use it like this
int decimal = Integer.parseInt("1234", 10);
int octal = Integer.parseInt("1234", 8);
int hex = Integer.parseInt("1234", 16);
This should do it:
String hex = "FA";
int intValue = Integer.parseInt(hex, 16);
And if you want to generate hex representation of an integer, use
String hex = Integer.toHexString(12);