How to convert an RGB component to a percentage in C?
How do I conver an RGB component (0-255) to a floating point number in which 255 wou开发者_StackOverflow中文版ld be 1.0f and 0 would be 0.0f?
What's wrong with dividing?
unsigned char red = 45;
float percentage = red/255.0f;
Like this:
int rgbValue = 123;
float fpValue = rgbValue / 255.0;
And if you have the entire rgb value in the int you have this option.
//Color Component Percents
#define CCP_ALPHA(argb) (((argb) & 0xFF000000) >> 24) / 255.0f
#define CCP_RED(rgb) (((rgb) & 0xFF0000) >> 16) / 255.0f
#define CCP_GREEN(rgb) (((rgb) & 0xFF00) >> 8) / 255.0f
#define CCP_BLUE(rgb) ((rgb) & 0xFF) / 255.0f
int main(int argc, char *argv[])
{
int argb = 0xCCDD33EE;
printf("Alpha %.2f%%\nRed %.2f%%\nGreen %.2f%%\nBlue %.2f%%\n",
CCP_ALPHA(argb) * 100,
CCP_RED(argb) * 100,
CCP_GREEN(argb) * 100,
CCP_BLUE(argb) * 100);
}
Output
Alpha 80.00%
Red 86.67%
Green 20.00%
Blue 93.33%
精彩评论