# RGB to hex and hex to RGB

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

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

Note: both versions 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-fd]{2})([a-fd]{2})([a-fd]{2})\$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 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-fd])([a-fd])([a-fd])\$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});

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