Skip to content

Instantly share code, notes, and snippets.

@bryc
Last active December 13, 2018 08:16
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 bryc/bd00326a1822b974d0a91ffb9d600a4e to your computer and use it in GitHub Desktop.
Save bryc/bd00326a1822b974d0a91ffb9d600a4e to your computer and use it in GitHub Desktop.
// Arbitrary precision base conversion, WIP
function baxx(str, src_base, dst_base) {
var number = [], output = "", res = [], quotient, remainder;
var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//decode
for(var i = 0; i < str.length; i++) number[i] = charset.indexOf(str[i]);
while (number.length) {
// divide successive powers of dst_base
quotient = [], remainder = 0;
for (var i = 0; i != number.length; i++) {
var accumulator = number[i] + remainder * src_base;
var digit = accumulator / dst_base | 0; // rounding faster than Math.floor
remainder = accumulator % dst_base;
if (quotient.length || digit) quotient.push(digit);
}
// the remainder of current division is the next rightmost digit
res.unshift(remainder);
// rinse and repeat with next power of dst_base
number = quotient;
}
//encode
for(var i = 0; i < res.length; i++) output += charset.charAt(res[i]);
return output;
}
baxx("7DhzpcifUHcRaLDZ24md9e", 62, 16); // ED436E326FC5B328D67BBEC0459A9DB2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment