Skip to content

Instantly share code, notes, and snippets.

@jed
Forked from 140bytes/LICENSE.txt
Created May 20, 2011 19:57
Show Gist options
  • Save jed/983661 to your computer and use it in GitHub Desktop.
Save jed/983661 to your computer and use it in GitHub Desktop.
convert HEX to RGB
function(
a // take a "#xxxxxx" hex string,
){
a = +( // turn it into a number by taking the
"0x" + // hexadecimal prefix and the
a.slice(1) // numerical portion,
.replace( // and
a.length > 4 // if the #xxxxxx form is used
&& /./g, // replace each character
'$&$&' // with itself twice.
)
);
return [ // return an array
a >> 16, // with red,
a >> 8 & 255, // blue,
a & 255 // and green components.
]
}
function(a){a='0x'+a.slice(1).replace(a.length>4&&/./g,'$&$&');return[a>>16,a>>8&255,a&255]}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jed Schmidt <http://jed.is>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "hex2rgb",
"description": "Converts a hex string to RGB.",
"keywords": [
"hex",
"color",
"rgb"
]
}
@jed
Copy link
Author

jed commented Jul 13, 2011

fixed. thanks again, @tsaniel!

@tsaniel
Copy link

tsaniel commented Oct 9, 2011

I find it we can save another byte.

function(a){a='0x'+a.slice(1).replace(a.length>4&&/./g,'$&$&');return[a>>16,a>>8&255,a&255]}

@jed
Copy link
Author

jed commented Oct 9, 2011

relentless golfing, @tsaniel!

@atk
Copy link

atk commented Oct 10, 2011

Wait, >4? Doesn't it need to be the other way round, <4?

@tsaniel
Copy link

tsaniel commented Oct 10, 2011

@atk: Thanks for your carefulness! i just did it anyhow.

@phoetry
Copy link

phoetry commented Dec 9, 2011

Both wrong with >4 and <4
Shound be a.length<5&&/./g

@slidenerd
Copy link

function hexToRgb(hex) {
var number = parseInt(hex, 16);
console.log(number)
var r = (number >> 16) & 255;
var g = (number >> 8) & 255;
var b = number & 255;
console.log(r,g,b)
return {red: r, green: g, blue: b};
}
let rgb = hexToRgb(0xFFFFFF)
Gives 119 114 21 , any ideas why

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment