converting an integer to rgb components


#1

I need a way to convert an integer to rgb values. Is this possible? I suspect it is, but I’m having a hard time understanding how to do it. I have done a fair amount of searching on google to little avail, but maybe I’m just not seeing things clearly.

I’m hoping to generate sequentially from 0-16777216 (256256256) and convert this number into red, green and blue components. I’m hoping to use this as a way of generating a sequential list of all the possible rgb colours.

C++ code would be most useful to me… but any explanation of what I need to do would be most helpful.


#2

Some like this?

#include <stdio.h>

int main(int argc, char** argv)
{
unsigned int rgba = 0x60708090;

int red = (rgba & 0xff000000) >> 24;
int green = (rgba & 0x00ff0000) >> 16;
int blue = (rgba & 0x0000ff00) >> 8;
int alpha = (rgba & 0x000000ff);
printf("0x%x, 0x%x, 0x%x, 0x%x
", red, green, blue, alpha);
return 0;
}


#3

The bitwise method is generally the fastest when dealing with packed data, but just to throw in some more ideas then another method which may be more suitable depending on your situation is to cast to unsigned chars or even a packed uchar structure.


#4

Perfect, thx guys just exactly what I needed.


#5

Yeah, that would be good. A union of an int and a 4 byte character array might be handy too.


#6

This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.