Colors and bitwise operators

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.

ActionScript
< view plain text >
  1. // From hex value to r,g,b values
  2. var hex:uint = 0xFF8811;
  3. var r:uint = rgb &gt;&gt; 16;
  4. var g:uint = rgb &gt;&gt; 8 &amp; 0xFF;
  5. var b:uint = rgb &amp; 0xFF;
  6.  
  7. //From r,g,b values to hex value
  8. hex = (r &lt;&lt; 16) | (g &lt;&lt; 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.