How to parse the hex color of a String on Integer

I am working on some code in Robolectric, namely IntegerResourceLoader . The following method throws a RuntimeException when rawValue is something like 0xFFFF0000 :

 @Override public Object convertRawValue( String rawValue ) { try { return Integer.parseInt( rawValue ); } catch ( NumberFormatException nfe ) { throw new RuntimeException( rawValue + " is not an integer." ); } } 

I tried using Integer.decode (String) , but this throws a NumberFormatException, although the grammar seems to be correct.

+4
source share
4 answers

decode() is the correct call method, but it does not work, because 0xFFFF0000 is above the maximum limit of 0x7fffffff for the integer. You might want to consider Long.

+6
source

The following method throws a RuntimeException when rawValue is something like 0xFFFF0000

This is because Integer.parseInt not designed to handle the 0x prefix.

I tried using Integer.decode (String), but that throws a NumberFormatException, although the grammar seems to be correct.

From Integer.decode Javadoc (related in your question):

This character sequence must be a positive value or a NumberFormatException will be thrown.

0xFFFF0000 is a negative number, and therefore, this probably causes the reason for the exception here.

Decision:

If you know that the specified value will be in the form 0x[hexdigits] , you can use Integer.parseInt(String, int) , which takes a radix value. For hexadecimal, the radix is ​​16. Like so:

 return Integer.parseInt(rawValue.split("[x|X]")[1], 16); 

This uses regex [x|X] to split the string, which will separate rawValue in lower or upper case of the character "x", and then passes it to parseInt with a radius of 16 for parsing it in hexadecimal format.

+2
source

Here's how android does it:

 private int parseColor(String colorString) { if (colorString.charAt(0) == '#') { // Use a long to avoid rollovers on #ffXXXXXX long color = Long.parseLong(colorString.substring(1), 16); if (colorString.length() == 7) { // Set the alpha value color |= 0x00000000ff000000; } else if (colorString.length() != 9) { throw new IllegalArgumentException("Unknown color"); } return (int)color; } throw new IllegalArgumentException("Unknown color"); } 
+2
source

If you can disable 0x from the front, you can set the radius of parseInt (). So Integer.parseInt(myHexValue,16)

For more details see http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String , int)

+1
source

Source: https://habr.com/ru/post/1432340/


All Articles