#### [SOLVED] RGB to hex and hex to RGB

By Sindar

How to convert colors in RGB format to hex format and vice versa?

For example, convert `'#0080C0'` to `(0, 128, 192)`. # Short arrow functions

For those who value short arrow function.

## Hex2rgb

A arrow function version of David's Answer

``````const hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];
``````

A more flexible solution that supports shortand hex or the hash `#`

``````const hex2rgb = h => {
if(h == '#') {H = h.slice(1)};
if(h.length <= 3) {h = h+h+h+h+h+h};
h = parseInt(h,16);
return [h >> 16 & 255,h >> 8 & 255, h & 255];
};
``````

## Rgb2hex

``````const rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
`````` Doesn't work with the hash (#ffffff). Nor with the 3 digit version with or without the hash (#fff / fff). #### @LeonNikolai 2020-08-10 09:27:37

Yes, I assume you strip unnecessary information beforehand. #### @Ron Gilchrist 2017-02-24 01:42:30

(2017) SIMPLE ES6 composable arrow functions

I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.

Note that this does not handle the alpha channel at all.

``````const arrayToRGBString = rgb => `rgb(\${rgb.join(',')})`;
const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
const rgbArrayToHex = rgb => `#\${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)\$/).splice(1, 3)
.map(v => Number(v));
const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));
``````

BTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do. #### @Kamil Kiełczewski 2020-02-21 22:39:14

Try (bonus)

``````let hex2rgb= c=> `rgb(\${c.substr(1).match(/../g).map(x=>+`0x\${x}`)})`;
``````

``````let hex2rgb= c=> `rgb(\${c.substr(1).match(/../g).map(x=>+`0x\${x}`)})`;

// TEST
console.log('#0080C0          -->', hex2rgb('#0080C0'));
console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));`````` #### @Roopesh 2020-05-01 15:34:34

A simple answer for rgb to hex

``````    function rgbtohex(r,g,b){
return "#" + (Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b)).toString(16));
}
`````` #### @Travis J 2020-02-18 03:11:17

Fairly straightforward one liner. Splits the rgb by commas, ignores non numerics, converts to hex, pads a 0, and finishes off with a hashbang.

``````var yellow = 'rgb(255, 255, 0)';
var rgb2hex = str => "#"+str.split(',').map(s => (s.replace(/\D/g,'')|0).toString(16)).map(s => s.length < 2 ? "0"+s : s).join('');

console.log(rgb2hex(yellow));`````` #### @Tim Down 2011-04-11 16:04:10

Note: both version of `rgbToHex` expect integer values for `r`, `g` and `b`, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

``````function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

Converting the other way:

``````function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})\$/i.exec(hex);
return result ? {
r: parseInt(result, 16),
g: parseInt(result, 16),
b: parseInt(result, 16)
} : null;
}

Finally, an alternative version of `rgbToHex()`, as discussed in @casablanca's answer and suggested in the comments by @cwolves:

``````function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

## Update 3 December 2012

Here's a version of `hexToRgb()` that also parses a shorthand hex triplet such as "#03F":

``````function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])\$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});

var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})\$/i.exec(hex);
return result ? {
r: parseInt(result, 16),
g: parseInt(result, 16),
b: parseInt(result, 16)
} : null;
} #### @Tim Down 2012-07-18 23:04:32

@Vitim.us: `<<` is the bitwise left shift operator. Assuming `g` is a non-zero integer, `g << 8` therefore effectively multiplies `g` by 256, adding to zeroes to the end of its hex representation. Likewise `r << 16` adds 4 zeroes. Adding `1 << 24` (1000000 in hex) ensures that the hex representation is left-padded with any required zeroes once the leading `1` is stripped off using `slice()`. For example, if `r` and `g` were both zero and `b` was 51, `((r << 16) + (g << 8) + b).toString(16)` would return the string "33"; add `1 << 24` and you get "1000033". Then strip the `1` and you're there. #### @WoodenKitty 2016-07-15 06:25:59

Would the bit shifting (eg `(r << 16)`) give the same result on both big and little endian computers? Edit: It does not. Here's why: stackoverflow.com/questions/1041554/… #### @Tim Down 2016-08-22 10:19:11

@Gothdo: Sorry to roll back your edit, but it's often not possible or practical to use ES6. The previous version will work anywhere. #### @Michał Perłakowski 2016-08-22 10:55:21

@TimDown OK, I posted this as my own answer. #### @Sandy Gifford 2017-05-15 21:32:59

Slight modification (may or may not be desirable). By using `/^#?([a-f\d])([a-f\d])([a-f\d])(?:[a-f\d]{1,2})?\$/i` for the short hand regex and `/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})(?:[a-f\d])*\$/i` for the long you can automatically throw out junk characters at the end of the string. #### @TheCrazyProfessor 2017-09-11 07:10:19

your rgbToHex doesn't work. get the funny result: #f55b2f00 #### @Tim Down 2017-09-11 15:03:44

@TheCrazyProfessor: For which version of `rgbToHex`, and with what input values? The second, alternative, version seems to fail with [256, 4, 4] #### @Tim Down 2017-10-16 09:59:19

@madprops: 256 is an invalid value. The acceptable range is 0-255 (integers only). Oh my bad. I was getting that value from another library. #### @user2977468 2018-06-25 15:48:04

Regarding the latest `rgbToHex` function. One will want to either typecast your passed rgb values as integers, or slightly modify the rgbToHex function. Example: jsfiddle.net/cydqo6wj Current: `return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);` Modified: `return "#" + ((1 << 24) + ((+r) << 16) + ((+g) << 8) + (+b)).toString(16).slice(1);` In the modified version, I simply force the rgb values to be evalued at integers prior to the change over to 16/hex. #### @Mike PG 2018-10-02 02:34:02

Additionally, you may want to implement a floor and ceiling to inputs. Just spent too much time chasing THAT unexpected madness down #### @Fabrice G 2018-10-06 10:34:00

@TimDown many thx, i just add in hexToRgb at begin `hex.toLowerCase();` #### @Guilherme 2019-01-11 12:27:56

a tip for pasing an rgba string `/^rgba\(?([\d]*)[\,\s]*([\d]*)[\,\s]*([\d]*)[\,\s]*([\d\.]*)‌​\)\$/i.exec('rgba(255‌​, 0, 12, 0.2)')` #### @2540625 2020-01-01 01:46:39

All three `rgbToHex` functions above risk failure when given non-integer decimal inputs: `rgbToHex(123.456, 0.101, 254.541); // "#7b00fe.8a7ef9e"` #### @Tim Down 2020-01-03 15:33:16

@jtheletter: Yes. Non-integer values were not valid in `rgb()` notation until very recently and are rounded by the browser. It's pretty trivial to add rounding. #### @marcobiedermann 2019-12-26 22:52:04

Immutable and human understandable version without any bitwise magic:

1. Loop over array
2. Normalize value if `value < 0` or `value > 255` using `Math.min()` and `Math.max()`
3. Convert number to `hex` notation using `String.toString()`
4. Append leading zero and trim value to two characters
5. join mapped values to string
``````function rgbToHex(r, g, b) {
return [r, g, b]
.map(color => {
const normalizedColor = Math.max(0, Math.min(255, color));
const hexColor = normalizedColor.toString(16);

return `0\${hexColor}`.slice(-2);
})
.join("");
}
``````

Yes, it won't be as performant as bitwise operators but way more readable and immutable so it will not modify any input #### @Jake 2019-10-05 20:05:53

I made a small Javascript color class for RGB and Hex colors, this class also includes RGB and Hex validation functions. I've added the code as a snippet to this answer.

``````var colorClass = function() {
this.validateRgb = function(color) {
return typeof color === 'object' &&
color.length === 3               &&
Math.min.apply(null, color) >= 0 &&
Math.max.apply(null, color) <= 255;
};
this.validateHex = function(color) {
return color.match(/^\#?(([0-9a-f]{3}){1,2})\$/i);
};
this.hexToRgb = function(color) {
var hex    = color.replace(/^\#/, '');
var length = hex.length;
return     [
parseInt(length === 6 ? hex['0'] + hex['1'] : hex['0'] + hex['0'], 16),
parseInt(length === 6 ? hex['2'] + hex['3'] : hex['1'] + hex['1'], 16),
parseInt(length === 6 ? hex['4'] + hex['5'] : hex['2'] + hex['2'], 16)
];
};
this.rgbToHex = function(color) {
return '#' +
('0' + parseInt(color['0'], 10).toString(16)).slice(-2) +
('0' + parseInt(color['1'], 10).toString(16)).slice(-2) +
('0' + parseInt(color['2'], 10).toString(16)).slice(-2);
};
};

var colors = new colorClass();
console.log(colors.hexToRgb('#FFFFFF'));//       [255, 255, 255]
console.log(colors.rgbToHex([255, 255, 255]));// #FFFFFF`````` #### @Wolden 2019-09-12 16:29:23

When you're working in 3D environment (webGL, ThreeJS) you sometimes need to create 3 values for the different faces of meshes, the basic one (main color), a lighter one and a darker one :

``````material.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube
``````

We can create these 3 values from the main RBG color : 255,0,0

``````function rgbToHex(rgb) {
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};

function convertToHex(r,g,b) {

var fact = 100;  // contrast
var code = '0x';

// main color
var r_hexa = rgbToHex(r);
var g_hexa = rgbToHex(g);
var b_hexa = rgbToHex(b);

// lighter
var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));
var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));
var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));

// darker
var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast
var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));
var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));

var hexa = code+r_hexa+g_hexa+b_hexa;
var light = code+r_light+g_light+b_light;
var dark = code+r_dark+g_dark+b_dark;

console.log('HEXs -> '+dark+" + "+hexa+" + "+light)

var colors = [dark, hexa, light];
return colors;

}
``````

In your ThreeJS code simply write:

``````var material = new THREE.MeshLambertMaterial();
var c = convertToHex(255,0,0); // red cube needed
material.color.set( Number(c), Number(c), Number(c) );
``````

Results:

``````//                                 dark      normal     light
convertToHex(255,255,255) HEXs -> 0x696969 + 0xffffff + 0xffffff
convertToHex(255,0,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(255,127,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(100,100,100) HEXs -> 0x292929 + 0x646464 + 0xa0a0a0
convertToHex(10,10,10) HEXs -> 0x040404 + 0x0a0a0a + 0x6a6a6a
``````  #### @Wolden 2019-09-12 16:36:35

Because colors depend of Light paramaters, play with the contrast (here 100) to obtain the expected result. #### @Aral Roca 2019-04-25 23:34:41

Bitwise solution normally is weird. But in this case I guess that is more elegant 😄

``````function hexToRGB(hexColor){
return {
red: (hexColor >> 16) & 0xFF,
green: (hexColor >> 8) & 0xFF,
blue: hexColor & 0xFF,
}
}
``````

Usage:

``````const {red, green, blue } = hexToRGB(0xFF00FF)

console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255
`````` #### @user2240578 2013-04-24 10:54:18

This snippet converts hex to rgb and rgb to hex.

View demo

``````function hexToRgb(str) {
if ( /^#([0-9a-f]{3}|[0-9a-f]{6})\$/ig.test(str) ) {
var hex = str.substr(1);
hex = hex.length == 3 ? hex.replace(/(.)/g, '\$1\$1') : hex;
var rgb = parseInt(hex, 16);
return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
}

return false;
}

function rgbToHex(red, green, blue) {
var out = '#';

for (var i = 0; i < 3; ++i) {
var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);

if (isNaN(n) || n < 0 || n > 255) {
return false;
}

out += (n < 16 ? '0' : '') + n.toString(16);
}
return out
}
`````` #### @Dunc 2016-10-19 13:22:22

Good as it handles shorthand, but could it return a structure rather than a string? #### @Anton Putov 2012-12-05 00:23:45

If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.

``````var canvas = document.createElement("canvas");
var ctx = this.canvas.getContext('2d');

ctx.fillStyle = "rgb(pass,some,value)";
var temp =  ctx.fillStyle;
ctx.fillStyle = "someColor";

`````` #### @Endless 2020-09-24 22:50:18

this is a grate way to convert any css color format and normalize it to hex, don't work in node unfortally but you could take adv of offscreenCanvas for web workers #### @K-Gun 2013-01-09 15:17:34

This could be used for getting colors from computed style propeties:

``````function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}

if (color.charAt(0) == "#") {
return color;
}

var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums, 10).toString(16),
g = parseInt(nums, 10).toString(16),
b = parseInt(nums, 10).toString(16);

return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}

// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>

console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
`````` #### @typhon 2013-08-04 13:57:15

Thank you for this. But there's a small error: should return `(r.length == 1 ? "0" + r : r)` and similarly for green and blue. # ECMAScript 6 version of Tim Down's answer

## Converting RGB to hex

``````const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
const hex = x.toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('')

console.log(rgbToHex(0, 51, 255)); // '#0033ff'``````

## Converting hex to RGB

Returns an array `[r, g, b]`. Works also with shorthand hex triplets such as `"#03F"`.

``````const hexToRgb = hex =>
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])\$/i
,(m, r, g, b) => '#' + r + r + g + g + b + b)
.substring(1).match(/.{2}/g)
.map(x => parseInt(x, 16))

console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]``````

## Bonus: RGB to hex using `padStart()` method

``````const rgbToHex = (r, g, b) => '#' + [r, g, b]

console.log(rgbToHex(0, 51, 255)); // '#0033ff'``````

Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code. #### @jamess 2018-10-20 20:11:14

hexToRgb() is easily adapted to handle 4 and 8 digit hex RGBA notation: `.replace(/^#?([a-f\d])([a-f\d])([a-f\d])\$/i,(m, r, g, b) => '#' + r + r + g + g + b + b)` becomes: `.replace(/^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])\$/i,(m, r, g, b, a) => '#' + r + r + g + g + b + b + a + a)` But is there a way to make the regexp work with A of RGBA as an optional 4th hex value? That would absolutely complete the functionality, making one regexp work with hex RGB and RGBA. Otherwise it's two regexps, one with 3 values, the other with 4. You must divide the 4th value by 255 to get the 4th arg for rgba(). #### @Eric Chen 2016-03-16 22:37:19

My version of hex2rbg:

1. Accept short hex like #fff
2. Algorithm compacity is o(n), should faster than using regex. e.g `String.replace, String.split, String.match` etc..
3. Use constant space.
4. Support rgb and rgba.

you may need remove hex.trim() if you are using IE8.

e.g.

``````hex2rgb('#fff') //rgb(255,255,255)
hex2rgb('#fff', 1) //rgba(255,255,255,1)
hex2rgb('#ffffff') //rgb(255,255,255)
hex2rgb('#ffffff', 1) //rgba(255,255,255,1)
``````

code:

``````function hex2rgb (hex, opacity) {
hex = hex.trim();
hex = hex === '#' ? hex.substr(1) : hex;
var bigint = parseInt(hex, 16), h = [];
if (hex.length === 3) {
h.push((bigint >> 4) & 255);
h.push((bigint >> 2) & 255);
} else {
h.push((bigint >> 16) & 255);
h.push((bigint >> 8) & 255);
}
h.push(bigint & 255);
if (arguments.length === 2) {
h.push(opacity);
return 'rgba('+h.join()+')';
} else {
return 'rgb('+h.join()+')';
}
}
`````` #### @user4639281 2016-03-16 22:47:22

Note that `h.join(',')` is the same thing as `h.join()`. #### @Rehan Haider 2018-04-10 12:02:47

A total different approach to convert hex color code to RGB without regex

It handles both `#FFF` and `#FFFFFF` format on the base of length of string. It removes `#` from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.

``````//Algorithm of hex to rgb conversion in ES5
function hex2rgbSimple(str){
str = str.replace('#', '');
return str.split('').reduce(function(result, char, index, array){
var j = parseInt(index * 3/array.length);
var number = parseInt(char, 16);
result[j] = (array.length == 3? number :  result[j]) * 16 + number;
return result;
},[0,0,0]);
}

//Same code in ES6
hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);

//hex to RGBA conversion
hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);

//hex to standard RGB conversion
hex2rgbStandard = str => `RGB(\${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;

console.log(hex2rgb('#aebece'));
console.log(hex2rgbSimple('#aebece'));

console.log(hex2rgb('#aabbcc'));

console.log(hex2rgb('#abc'));

console.log(hex2rgba('#abc', 0.7));

console.log(hex2rgbStandard('#abc'));`````` #### @Combine 2018-03-30 10:25:03

I wrote a modified version of the function of converting hexToRGB with the addition of safe checking if the r/g/b color components are between 0-255 and also the funtions can take Number r/g/b params or String r/g/b parameters and here it is:

`````` function rgbToHex(r, g, b) {
r = Math.abs(r);
g = Math.abs(g);
b = Math.abs(b);

if ( r < 0 ) r = 0;
if ( g < 0 ) g = 0;
if ( b < 0 ) b = 0;

if ( r > 255 ) r = 255;
if ( g > 255 ) g = 255;
if ( b > 255 ) b = 255;

return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex
}).join('');
}
``````

To use the function safely - you should ckeck whether the passing string is a real rbg string color - for example a very simple check could be:

``````if( rgbStr.substring(0,3) === 'rgb' ) {

let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
rgbStr = this.rgbToHex(rgbColors, rgbColors, rgbColors);

.....
}
`````` #### @zenw0lf 2019-09-13 05:35:43

This is not a modified version of hexToRGB, but of rgbToHex. #### @David 2012-07-16 16:06:02

An alternative version of hexToRgb:

``````function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;

return r + "," + g + "," + b;
}
``````

Edit: 3/28/2017 Here is another approach that seems to be even faster

``````function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);

return arrByte + "," + arrByte + "," + arrByte;
}
``````

Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way. #### @Pavlo 2013-09-15 12:02:25

A line of perfection: `return [r, g, b].join();`. #### @Pluto 2014-02-06 01:10:35

Or for the all-encapsulating one-liner solution: `return [(bigint = parseInt(hex, 16)) >> 16 & 255, bigint >> 8 & 255, bigint & 255].join();` #### @joews 2014-06-10 13:36:57

I am using this with one tweak - remove non-hex chars (like a leading `#`) before `parseInt`: `hex = hex.replace(/[^0-9A-F]/gi, '');` #### @Olav Kokovkin 2015-01-21 16:40:50

Don't be so quick to use the shorthand version. JSPerf shows that the one in this answer is fastest: jsperf.com/2014-09-16-hex-to-rgb #### @Maciej Krawczyk 2016-04-27 11:20:38

Be careful with this, its output isn't reliable. It made a color close to black appear dark pink. Better to use the function from top answer. #### @David 2016-04-27 14:30:05

I've never had it change a colour for me. The only catch is you have to send the hex values in as all 6 hex digits it doesn't support short form colours. (eg 999999 will work but 999 will not). What was the hex value you were trying to convert? #### @Shikatsu Kagaminara 2017-02-01 14:54:31

@OlavKokovkin Your test aren't very fair to begin with. The "fastest" function doesn't make the `join()`, which is imo the most time-consuming line in these functions. #### @m0sk1t 2014-10-27 07:52:47

My example =)

``````color: {
toHex: function(num){
var str = num.toString(16);
return (str.length<6?'#00'+str:'#'+str);
},
toNum: function(hex){
return parseInt(hex.replace('#',''), 16);
},
rgbToHex: function(color)
{
color = color.replace(/\s/g,"");
var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)\$/i);
if(aRGB)
{
color = '';
for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)\$/,'0\$1');
}
else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])\$/i, '\$1\$1\$2\$2\$3\$3');
return '#'+color;
}`````` #### @bit-less 2017-10-09 22:39:31

CSS Level 4 side note: Generally, the reason you'd want to be able to convert Hex to RGB is for the alpha channel, in which case you can soon do that with CSS4 by adding a trailing hex. Example: `#FF8800FF` or `#f80f` for fully transparent orange.

That aside, the code below answers both the questions in a single function, going from and to another. This accepts an optional alpha channel, supports both string an array formats, parses 3,4,6,7 character hex's, and rgb/a complete or partial strings (with exception of percent-defined rgb/a values) without a flag.

(Replace the few ES6 syntaxes if supporting IE)

In a line:

``````function rgbaHex(c,a,i){return(Array.isArray(c)||(typeof c==='string'&&/,/.test(c)))?((c=(Array.isArray(c)?c:c.replace(/[\sa-z\(\);]+/gi,'').split(',')).map(s=>parseInt(s).toString(16).replace(/^([a-z\d])\$/i,'0\$1'))),'#'+c+c+c):(c=c.replace(/#/,''),c=c.length%6?c.replace(/(.)(.)(.)/,'\$1\$1\$2\$2\$3\$3'):c,a=parseFloat(a)||null,`rgb\${a?'a':''}(\${[(i=parseInt(c,16))>>16&255,i>>8&255,i&255,a].join().replace(/,\$/,'')})`);}
``````

``````function rgbaHex(c, a) {
// RGBA to Hex
if (Array.isArray(c) || (typeof c === 'string' && /,/.test(c))) {
c = Array.isArray(c) ? c : c.replace(/[\sa-z\(\);]+/gi, '').split(',');
c = c.map(s => window.parseInt(s).toString(16).replace(/^([a-z\d])\$/i, '0\$1'));

return '#' + c + c + c;
}
// Hex to RGBA
else {
c = c.replace(/#/, '');
c = c.length % 6 ? c.replace(/(.)(.)(.)/, '\$1\$1\$2\$2\$3\$3') : c;
c = window.parseInt(c, 16);

a = window.parseFloat(a) || null;

const r = (c >> 16) & 255;
const g = (c >> 08) & 255;
const b = (c >> 00) & 255;

return `rgb\${a ? 'a' : ''}(\${[r, g, b, a].join().replace(/,\$/,'')})`;
}
}
``````

Usages:

`rgbaHex('#a8f')`

`rgbaHex('#aa88ff')`

`rgbaHex('#A8F')`

`rgbaHex('#AA88FF')`

`rgbaHex('#AA88FF', 0.5)`

`rgbaHex('#a8f', '0.85')`

`// etc.`

`rgbaHex('rgba(170,136,255,0.8);')`

`rgbaHex('rgba(170,136,255,0.8)')`

`rgbaHex('rgb(170,136,255)')`

`rgbaHex('rg170,136,255')`

`rgbaHex(' 170, 136, 255 ')`

`rgbaHex([170,136,255,0.8])`

`rgbaHex([170,136,255])`

`// etc.` #### @nachtigall 2017-04-04 11:22:51

Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less). #### @Entarra De'Lacord 2016-11-25 06:07:18

While this answer is unlikely to fit the question perfectly it may be very useful none the less.

1. Create any random element

`var toRgb = document.createElement('div');`

1. Set any valid style to the color you want to convert

`toRg.style.color = "hsl(120, 60%, 70%)";`

1. Call the style property again

`> toRgb.style.color;`

`< "rgb(133, 225, 133)"` Your color has been converted to Rgb

Works for: Hsl, Hex

Does not work for: Named colors #### @Panu Logic 2018-07-14 14:17:43

This may be the most practical answer when working with the browser. You often simply want to compare the color of some existing element to some known color expressed in #-notation. #### @IAmMilinPatel 2016-11-24 02:50:45

You can try this simple piece of code below.

For HEX to RGB

``````list(\$r, \$g, \$b) = sscanf(#7bde84, "#%02x%02x%02x");
echo \$r . "," . \$g . "," . \$b;
``````

This will return 123,222,132

For RGB to HEX

``````\$rgb = (123,222,132),
\$rgbarr = explode(",",\$rgb,3);
echo sprintf("#%02x%02x%02x", \$rgbarr, \$rgbarr, \$rgbarr);
``````

This will return #7bde84 #### @redestructa 2016-06-23 11:23:38

I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.

Just comment out the regex line if you know what you're doing and it's a tiny bit faster.

``````function hexToRGBA(hex, alpha){
hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
if (!/^(?:[0-9a-fA-F]{3}){1,2}\$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
if (hex.length==3){hex=hex+hex+hex+hex+hex+hex} //support short form
var b_int = parseInt(hex, 16);
return "rgba("+[
(b_int >> 16) & 255, //R
(b_int >> 8) & 255, //G
b_int & 255, //B
alpha || 1  //add alpha if is set
].join(",")+")";
}
`````` #### @Denis 2016-03-27 22:34:07

One-line functional HEX to RGBA

Supports both short `#fff` and long `#ffffff` forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.

``````function hexToRGBA(hex, opacity) {
return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}
``````

examples:

``````hexToRGBA('#fff')        ->  rgba(255,255,255,1)
hexToRGBA('#ffffff')     ->  rgba(255,255,255,1)
hexToRGBA('#fff', .2)    ->  rgba(255,255,255,0.2)
hexToRGBA('#ffffff', .2) ->  rgba(255,255,255,0.2)
hexToRGBA('fff', .2)     ->  rgba(255,255,255,0.2)
hexToRGBA('ffffff', .2)  ->  rgba(255,255,255,0.2)
`````` #### @Roko C. Buljan 2017-08-22 23:25:49

Try to write human-readable code, not one-liners. There's no gain if you minify your code before production anyways. This is what used. Good job! Only thing I added (apart from arrow function conversion) was (hex, opacity = 1). Yours would convert 0 to 1 which may not produce expected results. This is very readable code. I do not share the sentiment. #### @Rahul Raina 2016-03-01 13:07:36

Here is the Javascript code to change HEX Color value to the Red, Green, Blue individually.

``````R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
`````` #### @Ryano 2015-12-14 06:13:00

I found this...
http://jsfiddle.net/Mottie/xcqpF/1/light/

``````function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb,10).toString(16)).slice(-2) +
("0" + parseInt(rgb,10).toString(16)).slice(-2) +
("0" + parseInt(rgb,10).toString(16)).slice(-2) : '';
}
`````` #### @Sean Anderson 2015-12-01 23:21:34

I whipped up this for use with lodash. It will convert an RGB string such as `"30,209,19"` to its corresponding hex string `"#1ed113"`:

``````var rgb = '30,209,19';

var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
var intColor = _.parseInt(rgbValue);

if (_.isNaN(intColor)) {
throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
}

// Ensure a value such as 2 is converted to "02".
var hexColor = _.padLeft(intColor.toString(16), 2, '0');

return hexAccumulator + hexColor;
}, '#');
`````` #### @FelipeC 2013-11-04 10:04:19

Here's my version:

``````  function rgb2hex(red, green, blue) {
var rgb = blue | (green << 8) | (red << 16);
return '#' + (0x1000000 + rgb).toString(16).slice(1)
}

function hex2rgb(hex) {
// long version
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\$/i);
if (r) {
return r.slice(1,4).map(function(x) { return parseInt(x, 16); });
}
// short version
r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])\$/i);
if (r) {
return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); });
}
return null;
}
`````` #### @K. Kilian Lindberg 2014-02-08 11:21:14

cool, but the question was hex2rgb. Can you do it as short as this that would be nice :) #### @Goose 2015-07-10 16:20:00

Although it doesn't go both ways, I have to upvote this because for some reason the other rgb to hex solutions in this question were not working for me. #### @FelipeC 2015-08-25 21:01:55

The question was from rgb2hex first. Anyway I added my own hex2rgb. #### @hackjutsu 2017-09-11 17:43:45

A little bit confused about the `rgb2hex` method. Why do we add `0x1000000` to `rgb`, and why we need to call `.slice(1)` at last? #### @FelipeC 2017-11-15 15:40:17

Because blue would be #FF, we add 0x1000000, so it's #10000FF, and then we remove the first "1". #### @TurnerOC 2020-06-29 23:11:25

this also worked for me, when the other examples on this page didnt. i wanted to convert RGB 100, 100, 100 to HEX, other examples on this page returned "#100100100" - whilst this example, correctly returned "#646464" #### @srolfe26 2015-07-16 21:33:47

The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.

``````function RGBtoHex (red, green, blue) {
red = Math.max(0, Math.min(~~this.red, 255));
green = Math.max(0, Math.min(~~this.green, 255));
blue = Math.max(0, Math.min(~~this.blue, 255));

return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};
``````

The use of left shift '<<' and or '|' operators make this a fun solution too.

### [SOLVED] Converting Hex to RGB value in Python

• 2015-04-15 06:47:59
• Julian White
• 64356 View
• 66 Score
• Tags:   python colors rgb

### [SOLVED] How do you convert a byte array to a hexadecimal string, and vice versa?

• 2008-11-22 10:03:13
• alextansc
• 886474 View
• 1406 Score
• Tags:   c# arrays hex

### [SOLVED] Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

• 2011-04-06 00:39:35
• Pimp Trizkit
• 194465 View
• 530 Score
• Tags:   javascript colors hex

### [SOLVED] Convert JavaScript String to be all lower case?

• 2008-09-30 20:22:35
• Derek
• 452259 View
• 1307 Score
• Tags:   javascript string

### [SOLVED] How to convert hex to rgb using Java?

• 2010-11-09 01:20:38
• user236501
• 136122 View
• 96 Score
• Tags:   java colors

### [SOLVED] Convert hex color to RGB values in PHP

• 2013-03-04 12:53:49
• user123_456
• 82236 View
• 78 Score
• Tags:   php colors hex rgb