#### Archived

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

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

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

## Recommended Posts

i can easily convert 4 ints (r,g,b,a) into one DWORD, but how do i do the reverse?

##### Share on other sites

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

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
Thanks so much for the replies guys!

##### Share on other sites
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]

##### Share on other sites
that''s what a union does. maps the elements of the union to the same memory block

##### Share on other sites
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

1. 1
Rutin
67
2. 2
3. 3
4. 4
5. 5

• 21
• 10
• 33
• 20
• 9
• ### Forum Statistics

• Total Topics
633420
• Total Posts
3011793
• ### Who's Online (See full list)

There are no registered users currently online

×