在JavaScript中,有没有内置函数将整数从一个给定的基数转换为另一个给定的基数?我注意到已经可以使用toString(numberToConvertTo)
将十进制数转换为另一个基数,但我还没有找到可以从任何基数转换为任何基数的通用函数其他基地,如图所示:
convertFrom(toConvert, baseToConvertFrom, baseToConvertTo){
//convert the number from baseToConvertFrom to BaseToConvertTo
}
答案 0 :(得分:8)
致电parseInt(str, fromBase)
转换为基数10(或更确切地说,转换为实际数字),然后致电num.toString(toBase)
。
答案 1 :(得分:2)
您可能想要自定义输入或输出。您可能需要超过36个碱基。所以我做了这个
function baseCon(number,fromBase,toBase,fromChars,toChars) {
if (!fromChars) {
fromChars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
number = number.toString().toUpperCase();
}
if (!toChars) {
toChars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
}
if (typeof number != 'object') {
number = number.toString();
}
if (fromBase > fromChars.length) {
console.log('fromBase was too high');
} else if (toBase > toChars.length) {
console.log('toBase was too high');
} else {
if (fromBase == 10) {
var base10Num = Math.min(number);
} else {
var base10Num = 0;
var place = 0;
for (var index = number.length - 1; index > -1; index--) {
base10Num = base10Num + (fromChars.indexOf(number[index]) * Math.pow(fromBase,place));
place++;
}
}
var string = '';
var looping = true;
var stringLen = 0;
var stringVal = 0;
while (looping) {
stringLen++;
if (Math.pow(toBase,stringLen) == base10Num) {
stringLen++;
break;
} else if (Math.pow(toBase,stringLen) >= base10Num) {
break;
}
}
for (var placePos = stringLen; placePos > 0; placePos--) {
for (var placeVal = 0; placeVal < (toBase + 1); placeVal++) {
if (((placeVal * Math.pow(toBase,placePos - 1)) > (base10Num - stringVal)) || (placeVal == 0) && ((base10Num - stringVal) == 0)) {
if (!((placeVal == 0) && ((base10Num - stringVal) == 0))) {
stringVal = stringVal + ((placeVal - 1) * Math.pow(toBase,placePos - 1));
string = string + toChars[placeVal - 1];
} else {
string = string + toChars[0];
}
break;
}
}
}
if (stringVal == base10Num) {
return string;
} else {
console.log('baseCon failed');
return string;
}
}
};
您可以自定义输入字符,以便您可以执行此类操作
> baseCon([true,true,false,true,false],2,10,[false,true]);
< "26"
和粗略的输出字符
> baseCon('3942',10,8,false,['!','@','#','$','%','^','&','*']);
< "*^%&"
我花了一整天然后记得parseInt(number,fromBase).toString(toBase);
哈哈