THIS INFORMATION MAY BE INACCURATE I'M JUST EXPERIMENTING! If you find anything inaccurate please leave a comment ;).
I was brainstorming over stuff related to framework at school today. I remembered coming across some functions in OpenGL that let you pass colors off as a single integer but I forgot how the color was stored within this integer much less how each color component Red, Green and Blue was parsed out of it.
With a little bit research I found the formula for combining the color components together into a single integer, which is below.
int RGB = 256 * 256 * red + 256 * green + blue;
The harder portion is extracting each color component, so I setup a little test.
I plugged some stuff into the formula:
Red = <255, 0, 0> = 16711680
Green = <0, 255, 0> = 65280
Blue = <0, 0, 255> = 255
At first glance these numbers seemed to have no significance so I started messing around with them. Keep in mind, I'm not a mathematician and I generally suck at algebra.
I started trying a few things out for quite a long time and thought about bitwise operators, something that, though sad, I have not touched in a very long time. I remembered that a certain bitwise operator would decrease these numbers significantly. That operator was the bitwise right shift operator, >>.
I started doing some shifts on the red until I got something that seemed probable, shifting 16 bits to the right to get a proper color value for red. I did the same for green and ended up with 8. I'll go over blue later.
Here's an example:
Green = 65280 = 1111111100000000
1111111100000000 >> 8 = 0000000011111111
0000000011111111 = 11111111
11111111 = 255
There was only one problem though
What if I plugged in a green value in the formula that was greater than 255? Say 300? That's where the bitwise AND operator, &, comes in. It keeps the returned values within 255.
300 = 100101100
255 = 11111111
Doing a truth table for 300 & 255 would look like this:
300 = 100101100
000101100 = 44
Let's try another number that's is larger, something like 5032.
5032 = 1001110101000
0000010101000 = 168
What exactly does this mean? Well, it's simple the AND operator keeps it within the 0-255 range and wraps it around where needed.
Let's try and do 11111111 & 100000000(256)
000000000 = 0
See, it wraps around.
The blue value is quite easy, you don't need to do any shifts but you still need to do the bitwise AND with 255.
RandomColor = <0,10,255> = 2815 = 101011111111
000011111111 = 255
So the function I'll be using to parse integers to each color value will be:
void IntToRGB(int &r, int &g, int &b, int &rgb)
r = (rgb << 16) & 255;
g = (rgb << 8) & 255;
b = rgb & 255;
I haven't tried doing this in code but it all seems to work out on paper.