I have to convert a DWORD (unsigned long) RGBA to four int vars (R, G, B, and A) So far, I have this function to convert the 4 ints to a DWORD:
unsigned long
If you don't mind using byte-size integers for RGBA, you can use a union. [edit This is a commonly used approach and you are unlikely to find a compiler that doesn't suport it, but strictly speaking (so I'm told) it's an illegal hack. The better approach in most circumstances is to do a mathematical or binary conversion, but I'll leave this half of my answer in place because it may help the reader to understand what people are doing when they see this type of code out in the real world]
union RGBA { DWORD dword; unsigned char RGBA[4]; struct RGBAstruct { unsigned char b; unsigned char g; unsigned char r; unsigned char a; } };
Then you can access the green component as:
RGBA colour; int green = (int) colour.RGBA[2];
or
int green = (int) colour.RGBAstruct.g;
and access the DWORD value as
DWORD value = colour.dword;
If you need the RGBA values to be int values, or wish to use a conversion approach, then you need to use bitwise operators.
You are encoding them almost correctly, but you need to use bitwise OR operator |, not logical OR || operator:
DWORD value = (iA << 24) | (iR << 16) | (iG << 8) | iB;
To go in the reverse direction:
int iA = (value >> 24) & 0xff; int iR = (value >> 16) & 0xff; int iG = (value >> 8) & 0xff; int iB = (value) & 0xff;