I have a float RGBA which is from 0 to 1. I would like to convert it to int rgb
class Color
{
public:
float R, G, B, A;
Color(float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f);
}
I have a float RGBA which is from 0 to 1. I would like to convert it to int rgb
class Color
{
public:
float R, G, B, A;
Color(float r = 1.0f, float g = 1.0f, float b = 1.0f, float a = 1.0f);
}
[Edited] due to later "I want to convert the 32bit RGBA to 8bit R2G4B2"
[Edited again] due to "I'm using it on Embedded system, so static cast is not allowed"
[edited even more] due to "I'm using a c99 compiler" - so no C++
struct Color
{
float R, G, B, A;
}
int RGBAstructTo8bitRGB(const Color* color) {
if(NULL==color) { return 0; /* black */
unsigned r=(int)(3*(color->R < 0 ? 0 : this->R));
unsigned g=(int)(7*(color->G < 0 ? 0 : this->G));
unsigned b=(int)(3*(color->B < 0 ? 0 : this->B));
return (r<<6) | (g<<2) | b;
}
int RGBATo8bitRGB(float R, float G, float B) {
unsigned r=(int)(3*(R < 0 ? 0 : this->R));
unsigned g=(int)(7*(G < 0 ? 0 : this->G));
unsigned b=(int)(3*(B < 0 ? 0 : this->B));
return (r<<6) | (g<<2) | b;
}
void 8bitRGBtoRGBAstruct(int color, struct Color* dest) {
if(NULL!=dest) {
dest->R=(float)((color & 0x03)/3.0);
dest->G=(float)(((color >> 2) & 0x07)/7.0);
dest->B=(float)(((color >> 6) & 0x03)/3.0);
}
}
For a 24-bit RGB:
Ignore A
, scale the components to [0,255]
, shift-or them into an int:
class Color
{
public:
float R, G, B, A;
int toRGB() const {
unsigned r=(int)(255*(this->R < 0 ? 0 : this->R));
unsigned g=(int)(255*(this->G < 0 ? 0 : this->G));
unsigned b=(int)(255*(this->B < 0 ? 0 : this->B));
return (r<<16) | (g<<8) | b;
}
}