Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Last active October 13, 2015 03:12
Show Gist options
  • Save mattbell87/9d243cb6ad79f318c1c9 to your computer and use it in GitHub Desktop.
Save mattbell87/9d243cb6ad79f318c1c9 to your computer and use it in GitHub Desktop.
Convert from base10 to a custom base and back again

Base converter

I was playing around with numbering systems as I wanted some numbers to be represented by letters (or what you'd call Base 26).

A=0, B=1, C=2 etc..

When it gets to 26 it becomes BA, not AA as you might think to begin with. Think of it like the number 10. AA would equal zero just like 00.

I wrote this in plain JavaScript for easy testing, and it should be fairly straight-forward to port this to other languages if needed.

Usage

var base26 = new BaseConverter(); //or new BaseConverter("<custom base goes here>");
base26.toBase(123);
// returns "et"
base26.fromBase("et")
// returns 123

Custom base:

var hexa = new BaseConverter('0123456789abcdef');
var BaseConverter = function(base)
{
//Store the base as a string
this.base = base || 'abcdefghijklmnopqrstuvwxyz'; //default base
//Convert from normal (base 10) to the base above
this.toBase = function(num)
{
str = "";
//Get number of iterations
var iters = Math.floor(num / this.base.length);
//Get the remainder of the division
var remain = num % this.base.length;
//If the number is more than the base length, call this function on the iterations left
if (iters > 0)
str += this.toBase(iters);
//Store the symbol based on the remainder
str += this.base[remain];
return str;
}
//Convert from the base above back to normal (base 10)
this.fromBase = function(str)
{
var num = 0;
var multiplier = 1;
//iterate through the string backwards
for (var i = str.length - 1; i > -1; i--)
{
//find the index of the symbol
bIndex = this.base.indexOf(str[i]);
//update the result
num += bIndex * multiplier;
//update the multiplier
multiplier = multiplier * this.base.length;
}
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment