Skip to content

Instantly share code, notes, and snippets.

@daegalus
Created February 24, 2012 10:13
Show Gist options
  • Save daegalus/1899934 to your computer and use it in GitHub Desktop.
Save daegalus/1899934 to your computer and use it in GitHub Desktop.
Positional Notation Encoder/Decoder
var BASE02 = "01"; //Binary
var BASE04 = "0123";
var BASE08 = "01234567"; //Octal
var BASE10 = "0123456789"; //Decimal
var BASE16 = "0123456789ABCDEF"; //Hexadecimal
var BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var BASE62 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var BASE75 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_.,!=-*(){}[]"; //URL SAFE
function getValueOfDigit(digit, alphabet)
{
var pos = alphabet.indexOf(digit);
return pos;
}
function convert(src, srcAlphabet, dstAlphabet)
{
var srcBase = srcAlphabet.length;
var dstBase = dstAlphabet.length;
var work = src;
var val = 0;
var multiple = 1;
while (work.length > 0)
{
var digit = work.charAt(work.length - 1);
val += multiple * getValueOfDigit(digit, srcAlphabet);
work = work.substring(0, work.length - 1);
multiple *= srcBase;
}
work = val;
var output = "";
while (work >= dstBase)
{
var digitVal = work % dstBase;
var digit = dstAlphabet.charAt(digitVal);
output = digit + output;
work /= dstBase;
}
var digit = dstAlphabet.charAt(work);
output = digit + output;
return output;
}
var encoded = convert("1234567890",BASE10,BASE62); //Output: bv8h5u
var decoded = convert(encoded,BASE62,BASE10); //Output: 1234567890
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment