使用JavaScript将较大的base 62值转换为base 16
我需要使用JavaScript将一个base 62值(如4u8LPK581OHn7kRqRqP9ks)转换为base 16。使用a,我可以看到结果应该是12D08BC6D93BC4E8EA847434C960416 看一些npm结节,比如,我想我可以将值取为基数10,然后通过toString转换为基数16,如Base62。解码'4u8lpk581ohn7krqp9ks'。toString 16 但是,由于base 62的值很大,JavaScript希望使用科学符号表示它,该符号将转换为base 10,最后转换为base 16 我尝试使用解析基62值。但将基数限制为2-32使用JavaScript将较大的base 62值转换为base 16,javascript,math,base,Javascript,Math,Base,我需要使用JavaScript将一个base 62值(如4u8LPK581OHn7kRqRqP9ks)转换为base 16。使用a,我可以看到结果应该是12D08BC6D93BC4E8EA847434C960416 看一些npm结节,比如,我想我可以将值取为基数10,然后通过toString转换为基数16,如Base62。解码'4u8lpk581ohn7krqp9ks'。toString 16 但是,由于base 62的值很大,JavaScript希望使用科学符号表示它,该符号将转换为base
有人对另一种方法有什么建议吗?使用bigint并自己解码我认为单for循环编码并不难 不是JAVA程序员,所以我坚持使用C++/伪代码:
//base62Alphabet[] = {a,b,c,...,A,B,C,...,0,1,2,...};
bigint out;
char in[]="4u8LPK581OHn7kRqRqP9ks\0";
int i,d;
for (out=0,i=0;in[i];i++)
{
out*=62;
d=unsigned int(in[i]);
// here convert d from char to value from alphabet
// for example i found this base62Alphabet in that case
// (more common is that numbers are first instead of last)
if (d<unsigned int('A')) d+= 0-'a';
else if (d<unsigned int('0')) d+=26-'A';
else d+=52-'0';
out+=d;
}
// here out should hold your value
// so just print it in hex (bigint libs should have some function for that)
// or code it yourself it is similar code but instead *=62 you div/mod by 16
[附注]
这应该适用于MSB第一表示法。最有效的数字位于左侧的第一位
还要检查您的数字使用的字母表,并相应地更改代码
在某些平台上,需要从char进行无符号int转换
因为字符是有符号的,所以如果没有它,解码条件可能会出错。。。
这个
我有一个为JS中的通用基数转换编写的库,它可能会对您有所帮助。 节点REPL中的快速示例
> var PowerRadix = require('./lib/index');
undefined
> var base16 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
undefined
> new PowerRadix('4u8LPK581OHn7kRqRqP9ks', 62).toArray(base16)
[ 'A',
1,
2,
'D',
0,
8,
'B',
'C',
6,
'D',
9,
3,
'B',
'C',
4,
'E',
8,
'E',
'A',
8,
4,
7,
4,
3,
4,
'C',
9,
6,
0,
4,
1,
6 ]
> new PowerRadix('4u8LPK581OHn7kRqRqP9ks', 62).toString(base16)
'A12D08BC6D93BC4E8EA847434C960416'
我需要添加额外的文档和测试来显示这一点,但是您也可以将任何值的数组作为第二个参数传递给构造函数作为源基数。例如:
var base16 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
> new PowerRadix('4u8LPK581OHn7kRqRqP9ks', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')).toString(base16);
'A12D08BC6D93BC4E8EA847434C960416'
编辑:
添加了示例测试:
你试过这个吗:是的,但我遇到了同样的问题。在12个字符之后,JS切换到科学记数法并抛出结果。