How can I convert an RGB input into a decimal colo

2019-08-04 00:23发布

问题:

Say I have an rgb color code with values 255 for red, 255 for green and 0 for blue. How can I get the decimal color code from those numbers, using only mathematical operations? So my setup, in pseudo-code, would look like:

int r = 255;
int g = 255;
int b = 0;

int result = /*decimal color code for yellow*/

Please help, I have spent ages trying to find an answer already and would love a simple quick answer :)

回答1:

int result = (r * 256 * 256) + (g * 256) + b

Or, if your language has a bit shift operator,

int result = (r << 16) + (g << 8) + b


回答2:

In Python:

#!/usr/bin/python

# Return one 24-bit color value 
def rgbToColor(r, g, b):
    return (r << 16) + (g << 8) + b

# Convert 24-bit color value to RGB
def colorToRGB(c):
    r = c >> 16
    c -= r * 65536;
    g = c / 256
    c -= g * 256;
    b = c

    return [r, g, b]

print colorToRGB(rgbToColor(96, 128, 72))