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?
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
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);
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 & 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With