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.