RBG 24bit to RGB 8bit bit shifting

505 Views Asked by At

How do you store 3 numbers in a single byte using bit shifting in java, ie use the first 3 bits for R, the next 3 bits for G, and the last 2 bits B. I think I know how to retrieve the numbers from the bytes, however an example with encoding and decoding would be great.

Thanks Jake

EDIT:

The range of the values for R and G would be 0-7 and 0-3 for B.

1

There are 1 best solutions below

0
On

Given r, g and b are in the range 0 - 255:

rgb = (b >>> 6) << 6 | (g >>> 5) << 3 | (r >>> 5); 

This is filling out the result in this order:

+--+--+--+--+--+--+--+--+
|B7|B6|G7|G6|G5|R7|R6|R5|
+--+--+--+--+--+--+--+--+

i.e. I've assumed that when you've said "first" you meant least significant. If you want them the other way around it would be:

rgb = (b >>> 6) | (g >>> 5) << 2 | (r >>> 5) << 5;