# Questioning My RGB Code

• 01-02-2006
Epo
Questioning My RGB Code
Hullo again,

I've been trying to come up with code to parse out the Red, Green, and Blue channels from an unsigned long holding a colour.

I'll post my code then discuss my problem, if you can call it that...
Code:

```//For the sake of having something, which would give a heavy-blue colour since RGB actually means BGR unsigned long Colour = RGB(250, 100, 30); unsigned long B = Colour; unsigned long G = B >> 8;  //256 unsigned long R = G >> 16; //65536 //Only use the last 8 bits B = B & 255; G = G & 255; R = R & 255; //Used for shading //B = (unsigned long)(B * Ratio); //G = (unsigned long)(G * Ratio); //R = (unsigned long)(R * Ratio); Colour = RGB(B, G, R); //Should be the same colour we previously had, since shading is commented out```
Since a colour (unsigned long) can also be set using...
Code:

`Colour = 0x00FFAA22; //Let's use a hexadecimal number`
...I was under the suspicion that instead of shifting by 8 and 16, I should be shifting by 256 (16^2) and 65536 (16^4). However, this wasn't giving me my desired results (colours turned into grayscale), so after Googling, I found some samples using 8 and 16, with no explanation why.

I tossed it in, and for the longest time, it seemed like it was correct. Lately I noticed some discolourations as well, though. Even with my shading commented out. So I'm guessing that there's something wrong with the way I'm getting at the Red, Green, and Blue channels.

Bit-shifts and binary operators aren't my strong-suit, but I was confident I was using them correctly. Perhaps someone could enlighten me on where I went wrong?
• 01-02-2006
maxthecat
Now, I could be wrong here, but this is what I'm thinking:

Code:

```unsigned long G = B >> 8;  //256 unsigned long R = G >> 16; //65536```
This shifts it too far... Instead of shifting 8 bits to get the green channel, and then another 8 to get the red channel, you're shifting 8 to get the green channel, and then 24 (2^8 * 2^16)...

I think it might work if you do this:

Code:

```unsigned long G = B >> 8;  //256 unsigned long R = B >> 16; //65536```
• 01-02-2006
Epo
Oh, good call!

A fresh set of eyes is always handy, thanks for spotting that. The colours are back to good now.

My sand is coloured like sand, and dito for the rest.

(And you also solved my 256/65536 problem. Bit shifting shifts *shock* bits! So by using ">> 8" I'm shifting by eight bits. I was getting mixed up between multiplication/division by powers of 2 in order to shift.

It seems that for both problems, I took two valid methods, and created my own "half of each" third method.

Thanks again