1

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.

Amir Naghizadeh
  • 383
  • 3
  • 14
user1805792
  • 319
  • 1
  • 4
  • 17

2 Answers2

5

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.

NominSim
  • 8,447
  • 3
  • 28
  • 38
  • @Nomin.. Yeah that would work. But OP's `colorStr` contained: -`0xFF2f6b55`, that's why I said it won't work. `Ox` not needed. – Rohit Jain Nov 23 '12 at 23:55
  • 1
    @RohitJain Ah, well he said the "value" was `0xFF2f6b55`, and since he hinted that other values that he used worked I assumed he knew that the `0x` is superfluous. I'll edit my answer to reflect the assumption. – NominSim Nov 24 '12 at 00:05
1

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.

millimoose
  • 39,073
  • 9
  • 82
  • 134