C++ union data-structure, easy acccess of bits within a DWORD
- by TK
Im running through a set of DirectX tutorials online and I have the following structure:
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag
DWORD color; // from the D3DFVF_DIFFUSE flag
}
My basic understanding of directX leads me to thing tha color is made up of 8-bit alpha, red, green and blue channels.
I am attempting to get east access to these channels. Rather than write the following code numerous times (within the CUSTOMVERTEX structure):
public: int red()
{
return (color & 0x00FF0000) >> 16;
}
I could write a more elegant somution with a combination of a union and a structure e.g.
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag
#pragma pack(2)
union
{
DWORD color; // from the D3DFVF_DIFFUSE flag
struct
{
char a;
char r;
char g;
char b;
};
};
}
However this does not appear to function as expected, the values in r, g, & b almost appear the reverse of whats in color e.g. if color is 0x12345678 a = 0x78, r = 0x56. Is this an endieness issue?
Also what other problems could I be expecting from this solution? e.g. overflow from the color members?
I guess what Im asking is ... is there a better way to do this?!