const CHAR_TABLE = '0123456789ABCDEF'
// 将n进制转换为10禁止
function myParseInt(s, n = 10) {
let result = 0
for (let c of s) {
let value = CHAR_TABLE.indexOf(c)
// 非法范围,直接结束
if (value >= n || value < 0) break
result = result * n + value
}
return result
}
function decimalToNBase(value, n = 2) {
if (typeof value !== 'number') {
try {
value = parseInt(value)
} catch (err) {
throw new Error(`unable to parse ${value} as a Integer.`)
}
}
// 用递归栈特性,出栈顺序正好将结果倒置
if (value > 0) {
let remain = value % n
let divide = Math.floor(value / n)
return decimalToN(divide, n) + CHAR_TABLE[remain]
}
return '0'
}
console.log(myParseInt("011x", 8)) // 9
console.log(myParseInt("512", 16)) // 1298
console.log(myParseInt("EFF", 16)) // 3839
console.log(decimalToNBase(252, 2)) // 011111100
console.log(decimalToNBase(65321, 16)) // 0FF29
// 转换完成,又转换回来
console.log(myParseInt(decimalToNBase(65321, 16), 16)) // 65321
console.log(decimalToNBase(myParseInt('0FEA1', 16), 16)) // 0FEA1