Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created June 15, 2011 17:52
Show Gist options
  • Save kopiro/1027658 to your computer and use it in GitHub Desktop.
Save kopiro/1027658 to your computer and use it in GitHub Desktop.
Convert any number from base X to base X in Javascript
function base_converter(nbasefrom, basefrom, baseto) {
var SYMBOLS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (basefrom<=0 || basefrom>SYMBOLS.length || baseto<=0 || baseto>SYMBOLS.length) {
console.log("Base unallowed");
return null;
}
var i, nbaseten=0;
if (basefrom!=10) {
var sizenbasefrom = nbasefrom.length;
for (i=0; i<sizenbasefrom; i++) {
var mul, mul_ok=-1;
for (mul=0; mul<SYMBOLS.length; mul++) {
if (nbasefrom[i]==SYMBOLS[mul]) {
mul_ok = 1;
break;
}
}
if (mul>=basefrom) {
console.log("Symbol unallowed in basefrom");
return null;
}
if (mul_ok==-1) {
console.log("Symbol not found");
return null;
}
var exp = (sizenbasefrom-i-1);
if (exp==0) nbaseten += mul;
else nbaseten += mul*Math.pow(basefrom, exp);
}
} else nbaseten = parseInt(nbasefrom);
if (baseto!=10) {
var nbaseto = [];
while (nbaseten>0) {
var mod = nbaseten%baseto;
if (mod<0 || mod>=SYMBOLS.length) {
console.log("Out of bounds error");
return null;
}
nbaseto.push(SYMBOLS[mod]);
nbaseten = parseInt(nbaseten/baseto);
}
return nbaseto.reverse().toString().replace(/,/g, '');
} else {
return nbaseten.toString();
}
return "0";
}
@apanasara
Copy link

less precision for big integers due to limitation of parseInt

var x = "89999999179999999"; 
document.getElementById("input").innerHTML = "input : " + x;
x=base_converter(x,10,36);
document.getElementById("base36").innerHTML = "base36 : " + x;
document.getElementById("base10").innerHTML ="base10 : " + base_converter(x,36,10);

/*OUTPUT
input : 89999999179999999
base36 : OM6C4UCNKE8
base10 : 89999999180000000*/

@zamicol
Copy link

zamicol commented Nov 20, 2019

@apanasara, did you ever make a solution for bigger strings?

@zamicol
Copy link

zamicol commented Nov 23, 2019

Here's my solution that does not have the length limitations:

https://zamicol.github.io/BaseConverter/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment