After all these years working with JavaScript I am still learning things about its fundamentals. For example, did you know that the parseInt method accepts a second parameter that determines the base of the extracted number? You did? Well it was news to me.
I already knew that the toString method can be passed a radix to produce string representations of numbers in various bases. But now, with these two methods combined, I can see how base conversions in JavaScript can be ridiculously easy. This generic function is all that is needed:
function base2base(n, b1, b2) { return parseInt(String(n), b1).toString(b2); }
The first parameter (n) is the number (or string beginning with a number) we want to convert. The second (b1) is the base of that number, and the third (b2) is the base we want to convert to. If n cannot be interpreted as a number in base b1, the function returns NaN (Not-A-Number). Notice I explicitly cast n to a string in the body of the function. This is necessary so that octal an hexadecimal numbers are handled correctly.
As if that were not convenient enough, we can also write the following convenience functions that will handle any base conversion among binary, octal, decimal, and hexadecimal numbers:
function bin2oct(n) { return base2base(n, 2, 8); }
function bin2dec(n) { return base2base(n, 2, 10); }
function bin2hex(n) { return base2base(n, 2, 16); }
function oct2bin(n) { return base2base(n, 8, 2); }
function oct2dec(n) { return base2base(n, 8, 10); }
function oct2hex(n) { return base2base(n, 8, 16); }
function dec2bin(n) { return base2base(n, 10, 2); }
function dec2oct(n) { return base2base(n, 10, 8); }
function dec2hex(n) { return base2base(n, 10, 16); }
function hex2bin(n) { return base2base(n, 16, 2); }
function hex2oct(n) { return base2base(n, 16, 8); }
function hex2dec(n) { return base2base(n, 16, 10); }
The function below is an example of a practical (?) application of the functions above. It converts a CSS hexadecimal color value (sans leading ‘#’) to its RGB representation. It does not do any rigorous argument checking and assumes a valid 3- or 6-character string:
function colorHex2Rgb(hex) {
var i = hex.length / 3;
var r = hex.substr(0*i,i);
var g = hex.substr(1*i,i);
var b = hex.substr(2*i,i);
if (r.length == 1) r = r + r;
if (g.length == 1) g = g + g;
if (b.length == 1) b = b + b;
return 'rgb(' + [hex2dec(r),hex2dec(g),hex2dec(b)].join(',') + ')';
}
Perhaps not the most useful application of base conversion, but you get the idea.