JS實現進制間的轉換

目錄

使用原生方法實現

toString() 可以實現十進制轉其他進制

//十進制轉二進制
let num = 3
console.log(num.toString(2)) // 11
console.log(num)             // 3

toString()方法可把一個 Number 對象轉換爲一個字符串並返回
語法:NumberObject.toString(radix)

參數 描述
radix 可選。規定表示數字的基數,使 2 ~ 36 之間的整數。若省略該參數,則使用基數 10。

parseInt() 可以實現其他進制轉十進制

// 二進制轉10進制
let num = 110
console.log(parseInt(num,2)) // 6
console.log(num)             // 110

parseInt() 函數可解析一個字符串,並返回一個整數。
語法:parseInt(string, radix

參數 描述
string 必須,要被解析的字符串
radix 可選,要解析的數字的基數。2~36之間。若省略該參數或值爲0,則根據string來判斷數字的基數

實例:

parseInt("10");			//返回 10
parseInt("19",10);		//返回 19 (10+9)
parseInt("11",2);		//返回 3 (2+1)
parseInt("17",8);		//返回 15 (8+7)
parseInt("1f",16);		//返回 31 (16+15)
parseInt("010");		//未定:返回 10 或 8

parseInt()toString()結合可以實現各種進制之間相互轉換:

parseInt(num,8);   //八進制轉十進制
parseInt(num,16);   //十六進制轉十進制
parseInt(num).toString(8)  //十進制轉八進制
parseInt(num).toString(16)   //十進制轉十六進制
parseInt(num,2).toString(8)   //二進制轉八進制
parseInt(num,2).toString(16)  //二進制轉十六進制
parseInt(num,8).toString(2)   //八進制轉二進制
parseInt(num,8).toString(16)  //八進制轉十六進制
parseInt(num,16).toString(2)  //十六進制轉二進制
parseInt(num,16).toString(8)  //十六進制轉八進制

手寫JS實現

其他進制轉十進制
從右向左各位數字乘以基數的冪次方
例如:二進制 110 = 0*2^0 + 1*2^1 + 1*2^2 = 6

function fn(a,b){
    var arr = String(a)
    var sum = 0
    var p = arr.length
    for(let i=0,len=arr.length;i<len;i++){
        sum += Number(arr[p-1])*Math.pow(b,i)
        p--
    }
    return sum
}
console.log(fn(110,2))  // 6   二進制轉十進制
console.log(fn(11,8))   // 9  八進制轉十進制

十進制轉其他進制
除基取餘,倒序排序

function Stack() {
    let items = []
    this.push = function(e){
        items.push(e)
    }
    this.pop = function(e){
        return items.pop()
    }
    this.peek = function(e){
        return items[items.length-1]
    }
    this.isEmpty = function(e){
        return items.length === 0
    }
    this.size = function(){
        return items.length
    }
    this.clear = function(){
        items = []
    }
    this.print = function(){
        console.log(items.toString())
    }
}

function fn(num,base){
    let stack = new Stack()
    let rem // 餘數
    let baseString = ''
    let digits = '0123456789ABCDEF'
    while(num>0){
        rem = Math.floor(num%base)
        stack.push(rem)
        num = Math.floor(num/base)
    }
    while(!stack.isEmpty()){
        baseString += digits[stack.pop()].toString()
    }
    return baseString
}

console.log(fn(11,16)) // B
console.log(fn(3,2))   // 11
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章