如何在没有库或模块的纯JS中从base-36转换为base-62



我正在寻找一个JS脚本,它将转换一个基于36的数字,如:

23SQJ1LNEFSL00H18IVWABMP

以62为基数的数字,如:

1rZmfPo0xtnf8CLTfWRJh

我正在尝试翻译这个python代码来做到这一点。

转换器.py
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(num, alphabet=BASE62):
"""Encode a positive number in Base X
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
num, rem = divmod(num, base)
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)

我怎样才能做到这一点?

这是@RyanSmith找到的答案https://stackoverflow.com/a/32480941

function convertBase(value, from_base, to_base) {
var range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('');
var from_range = range.slice(0, from_base);
var to_range = range.slice(0, to_base);
var dec_value = value.split('').reverse().reduce(function (carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `'+digit+'` for base '+from_base+'.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}

这将基数10转换为基数62https://helloacm.com/base62/

// https://helloacm.com
// https://rot47.net
// base62.js
// provides conversion between base10 and base62
var Base62 = (function(){                
var table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function _to10(num)
{
var limit = num.length;
var res = 0;
for (var i = 0; i < limit; i ++)
{
res = 62 * res + table.indexOf(num.charAt(i));
}
return res;  
}
function _toBase(num)
{
var r = num % 62;
var res = table.charAt(r);
var q = Math.floor(num / 62);
while (q)
{
r = q % 62;
q = Math.floor(q / 62);
res = table.charAt(r) + res;
}
return res;
}
return {
FromBase10: function()
{
var r = [];
for (var i = 0; i < arguments.length; i ++)
{
var num = parseInt(arguments[i]);
r.push(_toBase(num));
}
return r;
},
FromBase62: function()
{
var r = [];
for (var i = 0; i < arguments.length; i ++)
{
var num = arguments[i].toString();
if (num.length)
{
r.push(_to10(num));
}
}
return r;    
}
} 
})();

最新更新