How can I convert from DWORD RGBA to ints?

I need to convert DWORD (unsigned long) RGBA to four int vars (R, G, B and A) So far I have this function to convert 4 int to DWORD:

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{
    return ((iA << 24) | (iR << 16) | (iG << 8) | iB);
}

How can I convert it?

Sort of

struct RGBA
{
    int R, G, B, A;
};

RGBA DWORD2RGBA(unsigned long dwColor)
{
    static RGBA tmp;
    //.......conversion process
    return tmp;
}

Any help would be appreciated! :)

thanks

+5
source share
4 answers

If I were you, I would stick to multiplicative additive operations in the functions of packing / unpacking. Something like that

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{        
  return ((iA * 256 + iR) * 256 + iG) * 256 + iB;
}

with symmetrical unpacking function

RGBA DWORD2RGBA(unsigned long dwColor)
{        
  RGBA tmp; /* why did you declare it static??? */

  tmp.B = dwColor % 256; dwColor /= 256;
  tmp.G = dwColor % 256; dwColor /= 256;
  tmp.R = dwColor % 256; dwColor /= 256;
  tmp.A = dwColor % 256; /* dwColor /= 256; */

  return tmp;
}

Note that there is only one “magic constant” in the entire code.

, , , , .

unsigned long RGBA2DWORD(int iR, int iG, int iB, int iA)
{        
  return (((((iA << 8) + iR) << 8) + iG) << 8) + iB;
}

RGBA DWORD2RGBA(unsigned long dwColor)
{        
  RGBA tmp; /* why did you declare it static??? */

  tmp.B = dwColor & 0xFF; dwColor >>= 8;
  tmp.G = dwColor & 0xFF; dwColor >>= 8;
  tmp.R = dwColor & 0xFF; dwColor >>= 8;
  tmp.A = dwColor & 0xFF; /* dwColor >>= 8; */

  return tmp;
}

" ".

/ , , /.

+9

RGBA, . [ . , , , , , ( ) . - , , , , ]

union RGBA
{
    DWORD dword;
    unsigned char RGBA[4];
    struct RGBAstruct
    {
        unsigned char b;
        unsigned char g;
        unsigned char r;
        unsigned char a;
    }
};

:

RGBA colour;
int green = (int) colour.RGBA[2];

int green = (int) colour.RGBAstruct.g;

DWORD

DWORD value = colour.dword;

RGBA int , .

, OR, || :

DWORD value = (iA << 24) | (iR << 16) | (iG << 8) | iB;

:

int iA = (value >> 24) & 0xff;
int iR = (value >> 16) & 0xff;
int iG = (value >> 8) & 0xff;
int iB = (value) & 0xff;
+3

, :

iA = rgb → 24; iR = (0x00FF0000 rgb) → 16; iG = (0x0000FF00 rgb) → 8; iB = (0x000000FF rgb);

+2

RGBA long :

int iR = (value) and 0xff;
int iG = (value → 8) and 0xff;
int iB = (value → 16) and 0xff;
int iA = (value → 24) and 0xff;

and the whole question is about BGRA (according to the question from the example), not RGBA.

+1
source

All Articles