# Shifting Bits

This is a discussion on Shifting Bits within the C Programming forums, part of the General Programming Boards category; If I use the code: #define RGB32BIT(a, r, g, b) ((b) + (g << 8) + (r << 16) + ...

1. ## Shifting Bits

If I use the code:
#define RGB32BIT(a, r, g, b) ((b) + (g << 8) + (r << 16) + (a << 24)

UINT pixel = RGB32BIT(0, 0, 255, 0);

How do I get back the alpha, red, green, and blue values if I just have the pixel?

2. alpha = (pixel >> 24) & 0xff;
red = (pixel >> 16) & 0xff;
green = (pixel >> 8) & 0xff;
blue = pixel & 0xff;

3. Congratulations! You have proven yourself to be among the ranks of the programmers that know too much. I knew the answer. I just wanted to see if anyone had a clue about it. I guess you do. I prefer:

Code:
```UCHAR alpha = pixel >> 24;
UCHAR red = pixel >> 16;
UCHAR green = pixel >> 8;
UCHAR blue = pixel;```
The
Code:
`UCHAR`
automaticaly drops off the extra so you don't need the
Code:
`& 0xFF`
. I put that up at the game programmers message board and I got all kinds of junk.

Code:
```b = pixel & 0x000000ff;
g = (pixel >> 8) & 0x000000ff;
r = (pixel >> 16) & 0x000000ff;
a = pixel >> 24;```

Congratulations! You have proven yourself to be among the ranks of the programmers that know too much. I knew the answer. I just wanted to see if anyone had a clue about it. I guess you do. I prefer:

Code:
```UCHAR alpha = pixel >> 24;
UCHAR red = pixel >> 16;
UCHAR green = pixel >> 8;
UCHAR blue = pixel;```
The
Code:
`UCHAR`
automaticaly drops off the extra so you don't need the
Code:
`& 0xFF`
. I put that up at the game programmers message board and I got all kinds of junk.
But in your original code a, g, b, and r aren't UCHAR's. So now you're changing their original types.

Getting back the Red, Green, and Blue

Congratulations! You have proven yourself to be among the ranks of the programmers that know too much.
You're a genious..

Code:
```union pixel_data
{
uint32_t pixel;
struct
{
uint8_t alpha;
uint8_t red;
uint8_t green;
uint8_t blue;
} part;
};```
Code:
```{
union pixel_data pix1;

pix1.pixel = 0x12345678;

printf("red: %d\n", pix1.part.red);
printf("green: %d\n", pix1.part.green);
printf("blue: %d\n", pix1.part.blue);
}```
Maybe? Not sure if word-alignment or padding would screw it up.

9. Code:
```enum { cAlpha, cRed, cGreen, cBlue };

union foo
{
uint32_t pixel;
uint8_t part[ sizeof( uint32_t ) ];
};

union foo bar;

printf("Alpha: %d\n", bar.part[ cAlpha ] );```
Or an array. Unions are definately fun.

Quzah.

10. Originally Posted by itsme86
Maybe? Not sure if word-alignment or padding would screw it up.
That depends on the order of the variables in the definition, and correct usage of #pragma pack(...)