利用进制转换压缩数字函数分享

时间:2021-05-25

复制代码 代码如下:
function zipNum(num, radix){
if(!zipNum.zip){
zipNum.zip = function(inputNum){
if(inputNum > 35){//用大写字母表示36-61
return String.fromCharCode('A'.charCodeAt(0) + inputNum % 36);
} else if(inputNum > 9){//用小写字母表示10-35
return String.fromCharCode('a'.charCodeAt(0) + inputNum % 10);
} else {
return inputNum;
}
}
}
var quotient = num, remainder, result;
if(radix > 36 && radix < 63){
result = [];
do {
remainder = quotient % radix;
quotient = parseInt(quotient / radix);
result.push(zipNum.zip(remainder));
}while(quotient > radix);
remainder = quotient % radix;
if(remainder !== 0){
result.push(zipNum.zip(remainder));
}
result = result.reverse().join('');
} else if(radix > 1 && radix < 36){
result = num.toString(radix);
} else {
result = num;
window.console && console.warn('radix argument must be between 2 and 62')
}
return result;
}

function testSortNum(){
assertEquals(zipNum(61, 62), 'Z');
assertEquals(zipNum(62 * 2 - 1, 62), '1Z');
assertEquals(zipNum(62 * 3 - 1, 62), '2Z');
assertEquals(zipNum(1361182624991, 62), 'dXN5fJB');
}
testSortNum();

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章