how to extract r,g,b components out of DWORD

Started by
6 comments, last by Cipher3D 20 years, 1 month ago
i can easily convert 4 ints (r,g,b,a) into one DWORD, but how do i do the reverse?
I eat heart attacks
Advertisement
Bit mask then bit shifts.

Say color == 0xFFFFFFFF. To extract red:

Do something like that:

int red = (color & 0xFF000000) << 96; // 96 == 6*16
int blue = (color & 0x00FF0000) << 64; // 64 == 4*16
etc..

Just experiment with the bit shift operator I''m not sure about it.


ph0ng^_^wh0ng
ph0ng^_^wh0ng
If, for example, your components are stored this way:

0x00RRGGBB

You would have to, in C, do this:

Color = 0x00F080F0;

Red = (Color >> 16);
Green = (Color >> 8) & 0xFF;
Blue = Color & 0xFF;

In fact, what I just did was shift the wanted bits and mask out the unwanted ones.
If you can, maybe represent your RGBA data like this in the first place:

struct RGBA{  union  {    struct { BYTE r, g, b, a; };    DWORD c;  };}


Then it''s simple enough. Otherwise I guess you could use bitshifts and the life to get the data:

void DWORD_To_RGBA(DWORD color, BYTE& r, BYTE& g, BYTE& b, BYTE& a){  r = (color & 0xFF000000) >> 24;  g = (color & 0x00FF0000) >> 16;  b = (color & 0x0000FF00) >> 8;  a = (color & 0x000000FF);}void RGBA_To_DWORD(DWORD& color, BYTE r, BYTE g, BYTE b, BYTE a){  color = (r << 24) | (g << 16) | (b << 8) | a;}


This assumes format is RGBA, you should be able to modify it to your needs.
Thanks so much for the replies guys!
I eat heart attacks
quote:Original post by porthios
struct RGBA
{
union
{
struct { BYTE r, g, b, a; };
DWORD c;
};
}

K so if I understand you right, c and r,g,b,a all pint to the same memory???



[edited by - deinesh on March 6, 2004 7:16:02 PM]
that''s what a union does. maps the elements of the union to the same memory block
I eat heart attacks
No, the union is between the dword and the struct, heres what it looks like, a D is a bye of the dword A R G B all are parts of the struct, the top and bottom are the same...

DDDD
RGBA so the first D is the same as the R, the G the same as the second D and so on
hope that helps
-Dan
When General Patton died after World War 2 he went to the gates of Heaven to talk to St. Peter. The first thing he asked is if there were any Marines in heaven. St. Peter told him no, Marines are too rowdy for heaven. He then asked why Patton wanted to know. Patton told him he was sick of the Marines overshadowing the Army because they did more with less and were all hard-core sons of bitches. St. Peter reassured him there were no Marines so Patton went into Heaven. As he was checking out his new home he rounded a corner and saw someone in Marine Dress Blues. He ran back to St. Peter and yelled "You lied to me! There are Marines in heaven!" St. Peter said "Who him? That's just God. He wishes he were a Marine."

This topic is closed to new replies.

Advertisement