Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created October 6, 2016 02:04
Show Gist options
  • Select an option

  • Save gkucmierz/3983688f61158465f8fa844c2b33f58a to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/3983688f61158465f8fa844c2b33f58a to your computer and use it in GitHub Desktop.
base conversion functions
let Alphabet = {
BINARY: '01',
OCTAL: '01234567',
DECIMAL: '0123456789',
HEXA_DECIMAL: '0123456789abcdef',
ALPHA_LOWER: 'abcdefghijklmnopqrstuvwxyz',
ALPHA_UPPER: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
ALPHA: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
ALPHA_NUMERIC: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
};
function convert(input, source, target) {
return fromNum(toNum(input, source), target);
}
function toNum(inp, str) {
return inp.split('').reduce((r, c, i) => {
let idx = str.indexOf(c);
return r + Math.pow(str.length, inp.length-i-1) * idx;
}, 0);
}
function fromNum(inp, str) {
let res = [];
let base = str.length;
while (inp) {
let tmp = inp % base;
res.unshift(str[tmp]);
inp = (inp - tmp) / base;
}
return res.join('') || str[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment