PDA

View Full Version : converting an integer to rgb components


Ian Jones
02-27-2007, 02:53 PM
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 (256*256*256) 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.

billrobertson42
02-27-2007, 06:47 PM
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\n", red, green, blue, alpha);
return 0;
}

Per-Anders
02-27-2007, 09:05 PM
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.

Ian Jones
02-28-2007, 12:59 AM
Perfect, thx guys just exactly what I needed.

billrobertson42
02-28-2007, 02:04 AM
cast to unsigned chars or even a packed uchar structure.

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

CGTalk Moderation
02-28-2007, 02:04 AM
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.