Skip to content

Instantly share code, notes, and snippets.

@krmgns
Created December 13, 2020 04:10
Show Gist options
  • Save krmgns/87f8d5aa0e6e861dda5e4d0bab3fd40a to your computer and use it in GitHub Desktop.
Save krmgns/87f8d5aa0e6e861dda5e4d0bab3fd40a to your computer and use it in GitHub Desktop.
convert_base.js
function convert_base(input, fromBase, toBase)
{
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
if (typeof fromBase == 'number') {
if (fromBase < 2 || fromBase > 62) {
throw ('Invalid base for from chars, min=2 & max=62')
}
fromBase = chars.substr(0, fromBase)
}
if (typeof toBase == 'number') {
if (toBase < 2 || toBase > 62) {
throw ('Invalid base for to chars, min=2 & max=62')
}
toBase = chars.substr(0, toBase)
}
input = '' + input
if (!input || fromBase == toBase) {
return input
}
const [inputLen, fromBaseLen, toBaseLen]
= [input.length, fromBase.length, toBase.length]
const numbers = []
for (var i = 0; i < inputLen; i++) {
numbers[i] = fromBase.indexOf(input[i])
}
var ret = ''
var oldLen = inputLen
do {
var newLen = div = 0
for (var i = 0; i < oldLen; i++) {
div = (div * fromBaseLen) + numbers[i]
if (div >= toBaseLen) {
numbers[newLen++] = (div / toBaseLen) | 0
div = div % toBaseLen
} else if (newLen > 0) {
numbers[newLen++] = 0
}
}
oldLen = newLen
ret = (toBase[div] ?? '') + ret
} while (newLen != 0)
return ret
}
console.log(convert_base('f8a8d807fa864a679049e0e9e8ab965a', 16, 62))
console.log(convert_base('f8a8d807fa864a679049e0e9e8ab965a', 16, 62) === '7zdg3qSDsAQGNYn94aRvYu')
console.log(convert_base('f8a8d807fa864a679049e0e9e8ab965a', 16, 36))
console.log(convert_base('f8a8d807fa864a679049e0e9e8ab965a', 16, 36) === 'epyqhxglnkss4a7jx2lrjlt96')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment