Skip to content

Instantly share code, notes, and snippets.

@hanigamal
Created April 9, 2012 16:30
Show Gist options
  • Save hanigamal/2344585 to your computer and use it in GitHub Desktop.
Save hanigamal/2344585 to your computer and use it in GitHub Desktop.
Convert a hex value to its decimal value
//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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment