Created
March 18, 2012 20:02
-
-
Save lrvick/2080648 to your computer and use it in GitHub Desktop.
Javascript functions for doing fast binary/hex/RGB color conversions using bitwise operations.
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
// convert 0..255 R,G,B values to binary string | |
RGBToBin = function(r,g,b){ | |
var bin = r << 16 | g << 8 | b; | |
return (function(h){ | |
return new Array(25-h.length).join("0")+h | |
})(bin.toString(2)) | |
} | |
// convert 0..255 R,G,B values to a hexidecimal color string | |
RGBToHex = function(r,g,b){ | |
var bin = r << 16 | g << 8 | b; | |
return (function(h){ | |
return new Array(7-h.length).join("0")+h | |
})(bin.toString(16).toUpperCase()) | |
} | |
// convert a 24 bit binary color to 0..255 R,G,B | |
binToRGB = function(bin){ | |
var pbin = parseInt(bin,2); | |
var r = pbin >> 16; | |
var g = pbin >> 8 & 0xFF; | |
var b = pbin & 0xFF; | |
return [r,g,b]; | |
} | |
// convert a hexidecimal color string to 0..255 R,G,B | |
hexToRGB = function(hex){ | |
var r = hex >> 16; | |
var g = hex >> 8 & 0xFF; | |
var b = hex & 0xFF; | |
return [r,g,b]; | |
} | |
// simple log function for web/nodejs | |
log = function(item){ | |
if (document.body){ | |
document.body.innerHTML = document.body.innerHTML+'<pre>'+item+'</pre>'; | |
} else { | |
console.log(item); | |
} | |
} | |
// convert some RGB color values to hex and to binary | |
new Array( | |
[000,000,000], // black | |
[000,255,000], // green | |
[255,255,255] // white | |
).forEach(function(rgb){ | |
var hex = RGBToHex(rgb[0],rgb[1],rgb[2]); | |
var bin = RGBToBin(rgb[0],rgb[1],rgb[2]); | |
log('-> RGB: '+rgb+' \n<- HEX: '+hex+' \n<- BIN: '+bin+'\n\n'); | |
}); | |
// convert some hexidecimal color values to RGB | |
new Array( | |
'000000', // black | |
'00FF00', // green | |
'FFFFFF' // white | |
).forEach(function(hex){ | |
var rgb = hexToRGB(parseInt(hex,16)); | |
log('-> HEX: '+hex+' \n<- RGB: '+rgb+'\n\n'); | |
}); | |
// convert some 24 bit binary color values to RGB | |
new Array( | |
'000000000000000000000000', // black | |
'000000001111111100000000', // green | |
'111111111111111111111111' // white | |
).forEach(function(bin){ | |
var rgb = binToRGB(bin); | |
log('-> BIN: '+bin+' \n<- RGB: '+rgb+'\n\n'); | |
}); |
the hex needs to start with "0x", for those who couldn't get it working
Array(7-h.length).join("0")
can be replaced with "0".repeat(6-h.length)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does the hexToRGB function do shorthex values as well?
UPDATE, it does not. I would suggest to do a check if length is less than 7 characters, if not duplicate each alphanumeric.