Skip to content

其他进制转十进制

其他进制转十进制

代码

javascript
export function getMapStringToNumber (base) {
  const res = {}
  if (base < 10) return res
  const strList = ['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']
  let curIndex = 10
  while (curIndex < base) {
    res[strList[curIndex - 10]] = String(curIndex)
    curIndex++
  }
  return res
}
typescript
export function getMapStringToNumber (base: number) {
  const res: { [key: string]: string } = {}
  if (base < 10) return res
  const strList = ['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']
  let curIndex = 10
  while (curIndex < base) {
    res[strList[curIndex - 10]] = String(curIndex)
    curIndex++
  }
  return res
}
javascript
// 其他进制转十进制
// 输入:binaryToDecimal('1010', 2)
// 输出:10

import { getMapStringToNumber } from "../../utilsJs"

export function otherBaseToDecimal (str, base) {
  if (base === 10 || base > 36 || base < 2) return Number(str)
  str = str.toLowerCase()
  let res = 0
  let digit = 0
  const strToNum = getMapStringToNumber(base)
  for (let i = str.length - 1; i > -1; i--) {
    const curStr = str[i]
    const curNum = strToNum[curStr] ? strToNum[curStr] : curStr
    res += Number(curNum) * Math.pow(base, digit)
    digit += 1
  }
  return res
}
typescript
// 其他进制转十进制
// 输入:binaryToDecimal('1010', 2)
// 输出:10

import { getMapStringToNumber } from "../../utils"

export function otherBaseToDecimal (str: string, base: number): number {
  if (base === 10 || base > 36 || base < 2) return Number(str)
  str = str.toLowerCase()
  let res = 0
  let digit = 0
  const strToNum = getMapStringToNumber(base)
  for (let i = str.length - 1; i > -1; i--) {
    const curStr = str[i]
    const curNum = strToNum[curStr] ? strToNum[curStr] : curStr
    res += Number(curNum) * Math.pow(base, digit)
    digit += 1
  }
  return res
}