I have a rather simple question: If I want to save a Color in the RGB spectrum, then what would be the most efficient way for saving it in the memory? (I am excluding wrapper classes, because that would depend on the language)
For example in Pseudo-Code:
int r = 255;
int g = 255;
int b = 255;
and
string rgb = "#FFFFFF";
are two ways to describe a rgb-value, but also there would be more space reserved then needed. I want to know if there is a "best" way to do this.
In my opinion, it may be the char
datatype, but you would need three of them and how would you save them efficient then?
While it might not be the most efficient way, storing all three 8 bit values in one int and if necessary using the remaining 8 bits for the alpha is a standard way to do this. For example (In C-like code):
int convert(int r, int g, int b, int a)
{
return (r << 24) | (g << 16) | (b << 8) | a;
}
int getR(int rgba)
{
return (rgba >> 24) & 0xFF;
}
To get the other values out, simply replace the shift by 24 with 16 for green, 8 for blue, 0 for alpha.
Storing three chars would also work just fine. A string uses much more memory than needed. But really, how many colors are you storing? Does your application use so many that the storage space is significant? If not, probably no need to worry about it.