# Convert int to Color

I am right now developing paint application in andengine because some features are only possible with andengine.

For this I have used color dialog box to use user selected color but that dialog box return int value. But my sprite use Color class for setting color.

Reverse thing is possible using,

getColor().getABGRPackedInt()


Using this I provide source color but after choosing I can't able to receive chosen color.

At present I use following dialog box.

Android Color Picker

Color value basically consists of 4 single byte channel values, these 4 value represent R, G, B and transparency(A) of that color. An integer value is also a 4 byte value, so these two types are used interchangeably. Based on the name of the function you are using I'm guessing the R is packed as the byte with lowest value, and A is the highest value byte. so to convert a color into packed integer format that function is basically computing

result = R + G * 256 + B * 256 * 256 + A * 256 * 256 * 256


this means the inverse function would be something like this:

R = packedValue % 256;
G = (packedValue / 256) % 256;
B = (packedValue / 256 / 256) % 256;
A = (packedValue / 256 / 256 / 256);


I might be wrong about the packing order but the idea behind that function is what I explained.

• You can use shift and and operators, they are faster than mod and div. So R = pv & 255; G = (pv >> 8) & 255; B = (pv >> 16) & 255; A = (pv >> 24) & 255; – ott-- Jul 6 '13 at 19:20
• @ott-- compilers usually convert dive operator into shift operators in optimization stage. and for those who are not comfortable with binary operations, using div and mod are much easier both to use and to understand. – Ali1S232 Jul 6 '13 at 19:23
• I don't really think mod and div would be easier to understand in THIS case. I mean, a newbie would think "how the heck multiplying and dividing can pack a color in an int?" Trying to explain this is much harder than explaining "because each 1 byte, or 8 bits is one color, that's what the shift and mask operators mean, you first move then get that moved part." – Gustavo Maciel Jul 6 '13 at 22:16
• @GustavoMaciel From mathematical point of view you are basically using a number in base 256. If you see that, modulo and division is easier to grasp. – MartinTeeVarga Jul 7 '13 at 3:54
• @sm4 From a logical point of view dissecting bits is easier to grasp...I guess it's rather subjective... – Sidar Jul 7 '13 at 19:24

You will need to use Java's bitwise operators to separate the color channels from the int value. Have a look at this: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html