function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(n) {
n = parseInt(n,10);
if (isNaN(n)) return "00";
n = Math.max(0,Math.min(n,255));
return "0123456789ABCDEF".charAt((n-n%16)/16)
+ "0123456789ABCDEF".charAt(n%16);
}
Notes: The script parses the input
R
,
G
,
B
values
as integers using the standard function
parseInt(string,10)
;
the second, optional argument
10
specifies that the value must be parsed as
a decimal number. (If we omit the
10
, the script would still work,
except for some input values starting with
0
, e.g.
009
or
011
,
where it might incorrectly assume
octal input.)
We use the standard functions
Math.min
and
Math.max
to make sure that the input values are within the range from 0 to 255.
The interested reader might notice that a nicer way to convert
n
to a hexadecimal string
is to use
n.toString(16)
; however, the above code was written
back in the ancient era when JavaScript 1.0 was still around, and the construct
n.toString(16)
won't work in JavaScript 1.0!