Functions to Convert a Hex Color String to RGB Values and Back
A couple of functions to convert between RGB values to a hex color value and back. One function will convert the given Red, Blue and Green values to a Hex code - the format of colour used in HTML. For example, if the values 255,255,255 is given, the hex code #FFFFFF must be returned. The other function will take the hex string as the argument and return an array with three values - red, blue and green.
I am creating a new JavaScript library. When I was testing it, I found that different browsers report the colour of an element in different ways. $("element").style.color will be '#ffffff' in one browser. In another it will be 'rgb(255, 255, 255)'. I wanted to make this consistant across all browsers in my library. So I got these color converter functions. Later I decided not to use them in my library - because, well, its not really necessary. So here is the code...
The code for the two hex convertion functions are given here.
- hex2num(hex)
- This function will accept a hex colour value(like #0FCAF8) and convert it to an array with three elements. The first element of the array will be the value of red, the second will be blue and the third one will be green. For example...
hex2num("#0FCAF8")
will return the value [15,202,248]. - num2hex(triplet)
- This function will take an array with three elements and return a hex value created from it. For example...
hex2num([15,202,248])
will return the value #0FCAF8.
Code
//Convert a hex value to its decimal value - the inputted hex must be in the
// format of a hex triplet - the kind we use for HTML colours. The function
// will return an array with three values.
function hex2num(hex) {
if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
hex = hex.toUpperCase();
var hex_alphabets = "0123456789ABCDEF";
var value = new Array(3);
var k = 0;
var int1,int2;
for(var i=0;i<6;i+=2) {
int1 = hex_alphabets.indexOf(hex.charAt(i));
int2 = hex_alphabets.indexOf(hex.charAt(i+1));
value[k] = (int1 * 16) + int2;
k++;
}
return(value);
}
//Give a array with three values as the argument and the function will return
// the corresponding hex triplet.
function num2hex(triplet) {
var hex_alphabets = "0123456789ABCDEF";
var hex = "#";
var int1,int2;
for(var i=0;i<3;i++) {
int1 = triplet[i] / 16;
int2 = triplet[i] % 16;
hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);
}
return(hex);
}