Skip to content

Instantly share code, notes, and snippets.

@mryellow
Created June 23, 2015 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mryellow/7fa748a3ba2134b5c834 to your computer and use it in GitHub Desktop.
Save mryellow/7fa748a3ba2134b5c834 to your computer and use it in GitHub Desktop.
JS convBase
/**
* Convert base.
*
* @param string number
* @param string fromBase
* @param string toBase
*
* @return string|integer
*/
var convBase = function(number, fromBase, toBase) {
if (fromBase == toBase)
return number;
var fromLen = fromBase.length;
var toLen = toBase.length;
var numberLen = number.length;
var retval = '';
if (toBase === '0123456789') {
var retvalNum = big(0);
for (i = 1; i <= numberLen; i++) {
retvalNum = retvalNum.plus(
big(fromBase.indexOf(number.charAt(i-1))).times(
big(fromLen).pow(numberLen-i)
)
);
}
return retvalNum.toFixed();
}
var base10;
if (fromBase !== '0123456789') {
base10 = convBase(number, fromBase, '0123456789');
} else {
base10 = number;
}
if (base10 < toBase.length)
return toBase.charAt(base10);
while (base10 >= 1) {
retval = toBase.charAt(big(base10).mod(toLen))+retval;
base10 = big(base10).div(toLen);
}
return retval;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment