In javascript
Encode
encodedData = (Math.floor((red / 32)) << 5) + (Math.floor((green / 32)) << 2) + Math.floor((blue / 64));
Decode
red = (encodedData >> 5) * 32;
green = ((encodedData & 28) >> 2) * 32;
blue = (encodedData & 3) * 64;
While decoding we are using AND Gate/Operator to extract desired bits and discard leading bits. With green, we would then have to shift right to discard bits at right.
While encoding Math.floor is used to truncate decimal part, if rounded off it would create total value greater than 255 making it a 9 bit number.
UPDATE 1
It does not provide accurate results if we divide color by 32 or 64.
RRRGGGBB
R/G = 3bit, max value is 111 in binary which is 7 in decimal.
B = 2bit, max value is 11 in binary which is 3 in decimal.
We should divide R/G by value equal or greater than 255/7 and B by value equal or greater than 255/3.
We should also note that in place of Math.floor we should use Math.round because rounding off gives more accurate results.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…