Skip to content

Instantly share code, notes, and snippets.

@keithamus
Created February 20, 2013 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keithamus/4995188 to your computer and use it in GitHub Desktop.
Save keithamus/4995188 to your computer and use it in GitHub Desktop.
RGB to HEX, HEX to RGB Can work with small hexes ('#000', '#f0c'), and RGB object ({r: 0, g: 0, b: 0})
function hex2rgb(hex) {
var int = parseInt(hex.replace(/^#/, '').replace(/^#/, '').replace(/^([\da-f])([\da-f])([\da-f])$/, '$1$1$2$2$3$3'), 16);
return {
r: (int >> 16) & 255,
g: int >> 8 & 255,
b: int & 255
};
}
function rgb2hex(r, g, b) {
if (isNaN(r)) g = r.g, b = r.b, r = r.r;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment