Question

I am trying to create color values from r,g,b values adding the alpha byte to create a color int.

But I am getting errors using :

Integer.valueOf(colorStr,16);

colorStr is the string that I build, now the value that sends me error is "0XFF2f6b55" it sends me invalid int.

Was it helpful?

Solution

Java's integer covers values from -2^31 to 2^31-1 (2147483647). Your value is (4281297749) in decimal which is too big for java's integer.

Java's long covers a much higher range of -2^63 to 2^63-1. Which includes your value, so a suggestion would be to use Long.valueOf(colorStr, 16) and switch to using longs. (A suggestion that comes into play when the values that you are working with are outside of the range of integer values).

It seemed to me that you were aware, but in case you were not; the 0x should be removed if it is part of the string value, as it will give an invalid format exception if left in.

OTHER TIPS

Your string is too big for a signed int - they go from -0x80000000 to 0x7FFFFFFF. Try:

int i = (int) Long.parseLong(colorStr.substring(2), 16);

This will result in a negative int, which might not be what you want. (When working with colors, it's probably more convenient to work with a tuple of values for the red, green, blue, and alpha component.)

Neither valueOf() or parseInt()/parseLong() will recognize the 0x prefix, you need to get rid of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top