Can someone explain to me how I would convert a hex code, ex: #FF9C19, to an rgb value, corresponding ex: (255, 156, 25), or the other way around using JavaScript?
I found a post that asked this but it was using python.
Can someone explain to me how I would convert a hex code, ex: #FF9C19, to an rgb value, corresponding ex: (255, 156, 25), or the other way around using JavaScript?
I found a post that asked this but it was using python.
0x
or &h
etc instead (you may need to consider this depending on your envionment)Putting these together and using a RegExp to extract the interesting bits and parseInt
to convert from the String representation of the base 16 numbers
function hex_to_RGB(hex) {
var m = hex.match(/^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i);
return {
r: parseInt(m[1], 16),
g: parseInt(m[2], 16),
b: parseInt(m[3], 16)
};
}
// ex.
hex_to_RGB('#FF0110') // {r: 255, g: 1, b: 16}
When converting in the opposite direction you would use num.toString(16)
and don't forget to pad the bytes with a '0'
if they're smaller than (dec) 16
If you're starting with an Integer i
which represents your hex colour, you can access the RGB values using bitwise operations, i.e.
var i = 0xFF0110, // 16711952
rgb = {
r: (i >> 16) & 0xFF, // or `(i & 0xFF0000) >> 16`
g: (i >> 8) & 0xFF, // or `(i & 0x00FF00) >> 8`
b: i & 0xFF // or ` i & 0x0000FF `
}; // {r: 255, g: 1, b: 16}, same as before
A legal hex color can be 3 or 6 characters after the '#', and rgb components
can be either percentages or numbers between 0 and 255.
function hexToRgb(c){
if(/^#([a-f0-9]{3}){1,2}$/.test(c)){
if(c.length== 4){
c= '#'+[c[1], c[1], c[2], c[2], c[3], c[3]].join('');
}
c= '0x'+c.substring(1);
return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
}
return '';
}
function rgbToHex(rgb){
var c= rgb.match(/\d+(\.\d+)?%?/g);
if(c){
c= c.slice(0, 3).map(function(next){
var itm= next;
if(itm.indexOf('%')!= -1){
itm= Math.round(parseFloat(itm)*2.55);
}
if(itm<0) itm= 0;
if(itm>255) itm= 255;
itm= Math.round(itm).toString(16);
if(itm.length== 1) itm= '0'+itm;
return itm;
});
return '#'+c.join('').toLowerCase();
}
return '';
}