js 进制转换
Posted 码小余の博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 进制转换相关的知识,希望对你有一定的参考价值。
递归写法
function baseConv(num, base, arr = [])
var quotient = ~~(num / base)
var remainder = num % base
arr.unshift(remainder)
if(quotient > 1)
return baseConv(quotient, base, arr)
else
arr.unshift(quotient)
var res = arr.join('')
if(base == 16)
res = "0x" + res
else if(base == 8)
res = "0" + res
else if(base == 2)
res = "0b" + res
return res
循环写法
function baseConv(num, base, arr = [])
var quotient = ~~(num / base)
for(;quotient > 1;)
quotient = ~~(num / base)
var remainder = num % base
arr.unshift(remainder)
num = quotient
arr.unshift(quotient)
var res = arr.join('')
if(base == 16)
res = "0x" + res
else if(base == 8)
res = "0" + res
else if(base == 2)
res = "0b" + res
return res
懂得自然懂,不必解释什么意思
代码是写的是10进制转任何进制的
以上是关于js 进制转换的主要内容,如果未能解决你的问题,请参考以下文章