I found this very interesting post called “Hex colors & bitwise operators” on www.tracestatement.com a while back and I’ve been meaning to blog about it.
- // From hex value to r,g,b values
- var hex:uint = 0xFF8811;
- var r:uint = rgb >> 16;
- var g:uint = rgb >> 8 & 0xFF;
- var b:uint = rgb & 0xFF;
- //From r,g,b values to hex value
- hex = (r << 16) | (g << 8) | b;
This tiny bit of code allows you to rapidly subtract the Red, Green and Blue values from a hexadecimal colour code. Once you have the R, G, B bits you can then manipulate them and once done convert them back to a single Hex value.
An important thing to remember is bitmasking, this can be used to switch a set of bits either on or off.