3

在 JavaScript 中,是否有任何内置函数可以将整数从一个给定的基数转换为另一个给定的基数?我注意到已经可以使用 将十进制数转换为另一个基数,但我还没有找到可以从任何基数转换为任何其他基数toString(numberToConvertTo)的通用函数,如下所示:

convertFrom(toConvert, baseToConvertFrom, baseToConvertTo){
    //convert the number from baseToConvertFrom to BaseToConvertTo
}
4

2 回答 2

9

调用parseInt(str, fromBase)以转换为基数 10(或者更确切地说,转换为实际数字),然后调用num.toString(toBase).

于 2013-01-21T22:08:13.253 回答
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);哈哈

于 2015-01-28T10:23:05.447 回答