How can I convert an RGB input into a decimal color code?

一个人想着一个人 提交于 2020-02-05 07:07:25

问题


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))


来源:https://stackoverflow.com/questions/25404998/how-can-i-convert-an-rgb-input-into-a-decimal-color-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!