## 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:

```// JS Hex/Number: Copyright 2007, John Resig
function toHex(){
var ret = "";
for ( var i = 0; i < arguments.length; i++ )
ret += (arguments&#91;i&#93; < 16 ? "0" : "") + arguments&#91;i&#93;.toString(16);
return ret.toUpperCase();
}

function toNumbers( str ){
var ret = &#91;&#93;;
str.replace(/(..)/g, function(str){
ret.push( parseInt( str, 16 ) );
});
return ret;
}&#91;/js&#93;

And then they can be used like so:
&#91;js&#93;toHex( 125, 255, 0 )
>> "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 Array.map( arguments, function(num){
return (num < 16 ? "0" : "") + num.toString(16);
}).join('');&#91;/js&#93;

and be able to have fun with the array comprehension of <a href="http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7">JavaScript 1.7</a>:
[js]function range(end) {
for (let i = 0; i < end; i++)
yield i;
}
&#91; i.toString(16) for ( i in range(16) ) &#93;&#91; num & 0x0F &#93;&#91;/js&#93;

<b>Update:</b> 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:

[js]num.toString(16)```

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.

Posted: May 2nd, 2007