#### Archived

This topic is now archived and is closed to further replies.

# quick color question

This topic is 6339 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i have a function for creating a 16bit 565 color value: unsigned short MAKECOLOR565(int r,int g,int b) { return ( (b%32) + ((g%64)<<6) + ((r%32)<<11) ); } what i can''t understand is how to extract the rgb values out from any 16bit color, so i could for example change the red intensity or something... i think the modulo is confusing me... hope you can help me out...

##### Share on other sites
The modulo should confuse you, because it is wrong.

  unsigned short MAKECOLOR565(int r,int g,int b){return ( (b%32) + ((g%64)<<6) + ((r%32)<<11) );}

should be

  unsigned short MAKECOLOR565(int r,int g,int b){return ( (b>>3) | ((g>>2)<<6) | ((r>>3)<<11) );}

To get the rgb values back out, you can use this....

  char GetRedComponent565(short c){ // you dont really need the &0xFF, its just there // for completeness... return (char) (c>>11)<<3)&0xFF;}char GetGreenComponent565(short c){ return (char) (c>>5)<<2)&0xFF;}char GetBlueComponent565(short c){ return (char) (c)<<3)&0xFF;}

HTH

##### Share on other sites
Duh - I forgot to mention the problem with that last solution....

If you use this method, you may well get some visible banding. (depends on your image) This is because you lost some data in the conversion to 16 bit, and converting back to 24 bit doesnt get it back. The only solution to this is to use some sort of dithering algorithm to get intermediate values - its a bit more than a one liner though...

##### Share on other sites

BTW:
the macro was from the book "tricks of the windows programming gurus", i think i''ll throw it right into my garbage can :-)))

##### Share on other sites
Hehe, I thought it might be (Ive seen that macro a million times )

TOTWGPG is a good book, but there are one or two blunders in the code... bear that in mind when copying the source..

##### Share on other sites
yeah, some code even wont compile :-)

but unforunately, i have to bother you again ( i''m confused again):

in your little snippet, youre using shorts and chars, why not unsigned shorts/chars so i have the full color palette from 0 to 65535?

and, what happens if the values go out of range, i.e. assigning 567 to my char? will the compiler clamp these values ( doing an implicit cast or something) ?

and (oh no one more :-) ), i loose some information with your functions ( i added the ''unsigned'' everywhere):

unsigned short color = MAKECOLOR565(255,0,0); //full red

unsigned char red = GetRedComponent(color);
// red == 248 now, lost some accuracy

sorry to bug you with that again....

1. 1
2. 2
Rutin
18
3. 3
khawk
15
4. 4
A4L
14
5. 5

• 9
• 13
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633744
• Total Posts
3013665
×