Colors and bitwise operators

Warning: Illegal string offset 'language' in /var/www/vhosts/ on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ on line 513

I found this very interesting post called “Hex colors & bitwise operators” on a while back and I’ve been meaning to blog about it.

  1. // From hex value to r,g,b values
  2. var hex:uint = 0xFF8811;
  3. var r:uint = rgb >> 16;
  4. var g:uint = rgb >> 8 & 0xFF;
  5. var b:uint = rgb & 0xFF;
  7. //From r,g,b values to hex value
  8. 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.