github地址 baseN
baseN: 可以将2的53次方以内的任意整数(包括负数)转化为字符串以及还原回该整数,可以自行配置进制和使用的字符。
安装
$ npm install basen
使用
详细使用可参见测试文件 baseN.test.js。
new BaseN()
三种方式新建baseN对象
var baseN = new BaseN();//使用默认的base: 52个英文字母和10个阿拉伯数字
var baseN = new BaseN(15);//设置为15进制,取’默认base‘的前15个char作为新的base
var baseN = new BaseN({
base:[
'a','b','c','d','e','0','1','2'
]
});//自定义base,这个例子是8进制
encode()
数字转为字符串
var testCase = [
[0, '0'],
[1, '1'],
[20, 'k'],
[1000, 'g8'],
[20130718, '1msV0']
];
var baseN = new BaseN();
testCase.forEach(function(item) {
baseN.encode(item[0]);
});
decode()
字符串还原数字
var testCase = [
[0, '0'],
[1, '1'],
[20, 'k'],
[1000, 'g8'],
[20130718, '1msV0']
];
var baseN = new BaseN();
testCase.forEach(function(item) {
baseN.decode(item[1]);
});
reBase()
重置base
var baseN = new BaseN();
baseN.reBase(10);//随机选取’默认base‘里的10个char作为新base
baseN.base.length == 10;//true
var testCase = [0, 1, 20, 1000, 1024, 123456789];
testCase.forEach(function(item) {
baseN.decode(baseN.encode(item))==item;//true
});