Question

I'm trying to represent each of the possible 65,536 colours of the 16 bit colour depth as a base 10 integer, but I'm having trouble.

Essentially I need to convert a base 10 number to a Color object representing that colour in the 16 bit spectrum. I think that base is important here, but I can't decide what base to go to.

Was it helpful?

Solution

The 16 bit color space uses 5 bits for the red channel, 6 for green and 5 for the blue channel. You can extract the values for each channel using bitwise operations.

int color = /* your 16 bit value here */

int red = color & 31;
int green = (color >> 5) & 63;
int blue = color >> 11;

To convert back, use

int color = red | green << 5 | blue << 11;

OTHER TIPS

A Color object contains a color in ARGB. A is for Alpha, which you don't need right now. The others are values for Red, Green and Blue. Each of them is an 8 bit value. Together, ARG and B form a 32 bit color.

16 bit colors are weird to begin with, because Red and Blue have 5 bits and Green has 6 bits.

To convert these to 8 bits, you can bit shift them (or multiply them).

int input = Your16BitColorValue;
var color = new Color;

color.R = input & 0x1F; /* Isolate 5 least significant bits */
color.G = (input & 0x7E0) >> 5; /* Isolate 6 middle bits and shift them 5 right */
color.B = (input & 0xF800) >> 11; /* Isolate left 5 bits and shift them right */

This is pretty accurate. For instance, for green, a 6 bit number, the highest value (all 6 bits set) is 63. The lower half of the bits set, results in 7 (1/9th of the max). When you shift that two places to convert to an 8 bit number, you get 28, which is also exactly 1/9th of 255. If you try a couple of other examples, you'll find that every example is pretty close. The biggest rounding errors, you find in the end of the spectrum. For instance 63, which is the brightest green in 16bit, will result in 252, which is almost the brightest green in 32 bit, but not exactly.

To solve that, you might use a factor, like this:

Value32 = Value16 * 255 / Max16Value

where Max16Value is either 31 (for red and blue) or 63 (for green). For instance:

Color.B = ((input >> 11) & 0x1F) * 255 / 31;

That way, a red of 31 in input will actually result in a red of 255 in the 32 bit color, which is the brightest value in both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top