Numbers, Hex, and Colors
Justin just made a post to his blog showing a nifty solution for converting an 8-bit number into a hex string, that's now built into Prototype.
I took the code, fleshed it out, and made a complementary function (converting from hex to a number). Here they are for you to enjoy:
// http://www.opensource.org/licenses/mit-license.php
function toHex(){
var ret = "";
for ( var i = 0; i < arguments.length; i++ )
ret += (arguments[i] < 16 ? "0" : "") + arguments[i].toString(16);
return ret.toUpperCase();
}
function toNumbers( str ){
var ret = [];
str.replace(/(..)/g, function(str){
ret.push( parseInt( str, 16 ) );
});
return ret;
}
And then they can be used like so:
>> "7DFF00"
toNumbers( "7DFF00" )
>> [ 125, 255, 0 ]
I love using the "secret" extra argument to parseInt - allowing to specify the base of the number that you're parsing. You simply up it to 16 and you now have a dead-simple hex-to-number convertor.
If we had JavaScript 1.6 today we'd be able to use Array.map() to make some of the above less painful, like so:
return (num < 16 ? "0" : "") + num.toString(16);
}).join('');
and be able to have fun with the array comprehension of JavaScript 1.7:
for (let i = 0; i < end; i++)
yield i;
}
[ i.toString(16) for ( i in range(16) ) ][ num & 0x0F ]
Update: So you can specify the base of a number in the number's .toString(). Huh, you learn something new everyday! In retrospect, I don't know why I was doing the array comprehension at all when I could've just done this:
Side Note: It really irks me that there's no built-in "range" utility for array comprehension. Maybe if the comprehension wasn't limited to just for..in loops, and it included normal for loops, instead? Oh well, water under the bridge at this point.
Tags: numbers, javascript, programming, colors
20 Comments on 'Numbers, Hex, and Colors'



