Search code examples
javascriptc++colorsbinary

Convert a RGB colour value to Decimal


How do I convert a RGB colour value to just plain decimal?

So I have: RGB(255,255,255) is white
Its decimal equivalent is: 16777215

I have tried thinking it might just be:

var dec = r*g*b; // but this doesn't work

Although that doesn't work.

Anyone know of the algorithm/equation to convert from RGB (or rgba) to decimal?


Solution

  • RGB integers are typically treated as three distinct bytes where the left-most (highest-order) byte is red, the middle byte is green and the right-most (lowest-order) byte is blue. You can retrieve the values of these individual bytes like this:

    var c = 0xff03c0; // 16712640
    var components = {
        r: (c & 0xff0000) >> 16, 
        g: (c & 0x00ff00) >> 8, 
        b: (c & 0x0000ff)
    };
    

    You can re-create a color from its components by shifting the bytes back in:

    c = (components.r << 16) + (components.g << 8) + (components.b);
    

    In your case, simply substitute components.r (etc) with your actual variables.