Search code examples
javaintegervalue-of

Integer.valueOf() invalid int


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.


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.