Explode RGB Unsigned Integer into Individual R, G and B Values + RGBA

At irregular intervals I need to take a RGB uint – e.g. 0 is rgb(0,0,0) and 16711680 is red (#ff0000) and convert it to an unsigned integer and visa-versa.
I need this from time-to-time and always forget. That, and somehow I misplace the code or leave it behind with my employer. I will now forget no more thanks to “Splitting an RGB uint into its separate R G B components” question on stackoverflow and this post.


Here’s the run down (in AS3)…

Convert RGB to uint (decimal):

Convert uint (decimal) to RGB:


So after implementing some of this, I thought… "what about alpha channel support?" Well keep in mind, alpha is a graceful implementation/add-on and does not obstruct (or shift) the original data of the RGB value.

With this in mind, note that alpha is in the upper bit range (24); in hexadecimal format that is #AARRGGBB. It is doubly important to make sure that an unsigned integer is being used. With just normal RGB you can get away with a signed integer (−2,147,483,648 to 2,147,483,647) since you don’t need higher values, but you need unsigned for RGBA (0 to 4,294,967,295). For example, #FFFFFF for RGB merely equates to 16,777,215 in decimal format which is well under the 32-bit signed integer maximum (one-twenty-eight to be exact, think about it), however #FFFFFFFF for RGBA equates to 4,294,967,295 which is the exact maximum of a signed 32-bit integer (e.g. uint.MAX_VALUE).

Moral of the story: don’t use datatypes of “Number” or “int,” just “uint.”

Anyways, here’r the goods, going from uint (decimal) to RGBA (errr, ARGB?):

And going from RGBA to uint (decimal, base 10):

Further Reading