-
-
Save jed/983661 to your computer and use it in GitHub Desktop.
convert HEX to RGB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function(a){a='0x'+a.slice(1).replace(a.length>4&&/./g,'$&$&');return[a>>16,a>>8&255,a&255]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "hex2rgb", | |
"description": "Converts a hex string to RGB.", | |
"keywords": [ | |
"hex", | |
"color", | |
"rgb" | |
] | |
} |
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]}
relentless golfing, @tsaniel!
Wait, >4
? Doesn't it need to be the other way round, <4
?
@atk: Thanks for your carefulness! i just did it anyhow.
Both wrong with >4
and <4
Shound be a.length<5&&/./g
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
fixed. thanks again, @tsaniel!