Here is the "magic" code that would take a 24-bit RGB value and search the 256 color palette for the closest match. It's super-hyper optimized (loop unrolling, etc). This way I could, for example, overdraw the buffer semi-transparently multiple times with random offsets for a screen shake effect.