Shifting vs. Scaling

   
   
   
   

With the advent of the web, colours expressed in numerical form have become much more prevalent, while CSS supports named colours, the most common way is to use the hexadecimal RGB (Red Green Blue) format. A pure blue colour would be represented as #F00000 or #F00. The first format represents the colour as three 8 bit values, the second as three 4 bit values. People often use the 4 bit format because it is shorter and the difference are very minor.

If you look at the box on the side, it contains sixteen red blocks, specified each with a slightly different shade of red, the darkest at the top-left edge, the lightest at the bottom right. Many mobile screen cannot display 24 (3×8) bits colour, but handle a more conservative 15 (3×5) bits. The old web-safe colour table further restricted the set of colours to six hex values per channel: 0, 3, 6, 9, C and F, for a total of 216 colours.
Converting from 8 bit data to 4 bits is very easy, you just shift right and drop the superfluous bits. So the binary 11110000 becomes 1111. How do you do the reverse conversion? The naive version is to simply shift to the left, so 1111 becomes 11110000. This is a very bad solution, imagine you are converting from a 2 bit per channel model to 8 bit per channel model. So you convert 11 to 11000000 so a red block would become dark red instead of bright red .

So instead of shifting, the proper way is do scaling. This can of course be done mathematically, in this case, if c is your 4 bit colour, then your 8 bit colour is 256 × (c ÷ 4). The quick way to do this with bit manipulation is to replicate the short bit sequence in the long format, so the new binary value would be 11111111, first the shifted bits 11, then the same bits replicated for each sequence of two bits.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.