Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 419
sazr Avatar asked Dec 12 '11 01:12

sazr


3 Answers

A much better answer (in terms of clarity) is this:

'Convert RGB to LONG:
 LONG = B * 65536 + G * 256 + R

'Convert LONG to RGB:
 B = LONG \ 65536
 G = (LONG - B * 65536) \ 256
 R = LONG - B * 65536 - G * 256

LONG is your long integer (decimal) that you want to make. Easy huh? Sure, bitshift

like image 87
Sam Brown Avatar answered Oct 19 '22 23:10

Sam Brown


if (color.substr(0, 1) === '#') {
    return color;
}
var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
var red = parseInt(digits[2]);
var green = parseInt(digits[3]);
var blue = parseInt(digits[4]);
var rgb = blue | (green << 8) | (red << 16);
return rgb.toString(10);
like image 43
sharon_antony Avatar answered Oct 19 '22 22:10

sharon_antony


I agree that bitshift is clearer and probably better performance.

That said, if you want a math answer due to language support (such as doing this in a spreadsheet) modulus % and trunc() or floor() make it simple:

Assuming 8 bit values for red green and blue of course (0-255):

var rgbTotal = red * 65536 + green * 256 + blue;

var R = Math.trunc( rgbTotal / 65536 );
var G = Math.trunc( ( rgbTotal % 65536 ) / 256 );
var B = rgbTotal % 256;

Discussion: Pointing to sam's answer, RGB values are nearly always big endian in terms of order, certainly on webpages, jpeg, and png. Personally I think it's best to multiply red by 65536 instead of blue, unless you're working with a library that requires it otherwise.

To return to separate values:

  • For R, just divide by 65536 and truncate the remainder.
  • For G, we discard R via mod 65536 then dividing by 256, truncating the remainder (remainder is blue).
  • For B, we take mod 256, which disposes of the two higher bytes.

For R & G the number needs to be truncated to discard the remainder, language specific, mainly we want the integer. In javascript Math.trunc() is the easy way, and Math.floor() also works. It's not needed for B as that IS the remainder from the modulus — however this also assumes that we don't need error checking such as from user input, i.e. the value for B is always an integer 0-255.

like image 36
Myndex Avatar answered Oct 20 '22 00:10

Myndex