Base Conversion

Converting between number bases isn't something you need to do very often in JavaScript. It also isn't something that is all that obvious how to do either. Some people are at least aware that the parseInt() built in function takes a second parameter to specify the number base to convert from in converting to base ten but fewer realise that the Number.toString() method can be used to convert from base ten to a different number base.

To simplify converting between base 10 and other number bases we can define the JavaScript equivalent of a class to allow us to define an object for any selected number base that will then have toDec() and fromDec() methods for converting numbers from the specified base to decimal (base 10) and from base ten to that specified number base.

To define this "class" we need just three lines of JavaScript. We can then define an object based on this "class" specifying the number base that our new object is to use.

Here is the code to define our "class":

var Base = function(b) {this.base = b;};
Base.prototype.toDec = function(n) {return parseInt(n,this.base);};
Base.prototype.fromDec = function(n) {return n.toString(this.base);}

We now use that to define an object for each base we want to be able to convert to and from base 10. The following shows examples of how to create objects for converting to and from base 16 and base 20.

var b16 = new Base(16);
var b20 = new Base(20);

With these two objects defined we can now pass values in the appropriate number base to their toDec() and fromDec() methods in order to do our conversions. The following show examples of converting from base 16 to base 10, from base 10 to base 16, from base 20 to base 10, from base 10 to base 20, and finally from base 16 to base 20 (by making use of both objects together).

b16.toDec('af') // 175
b16.fromDec(56) // '38' base 16
b20.toDec('af') // 215
b20.fromDec(56) // '2g' base 20
b20.fromDec(b16.toDec('af')) // '8f' base 20

Using the code we can make out our number base conversions much easier to read.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow