二進制和十進制相互轉換、位移運算

二進制和十進制相互轉換、位運算

記錄下在codewar上作的一個題目和收穫函數

128.32.10.1 == 10000000.00100000.00001010.00000001code

Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: 2149583361ip

Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address.get

Example : 2149583361 ==> "128.32.10.1"string

本身的解題思路是將十進制的數轉爲二進制(不足32位補0),而後依次取8位轉化爲十進制的數字,再用.鏈接即爲IPit

裏面的幾個點記錄一下:io

  • 十進制轉換爲二進制 numObj.toString([radix]) radix能夠指定進制,默認爲10
let x = 2149583361;
    x.toString(2) //  "10000000001000000000101000000001"
  • 二進制轉換爲十進制 Number.parseInt(string[, radix]) radix能夠指定進制,默認爲10
Number.parseInt("10000000001000000000101000000001",2) // 2149583361
  • 不足32位時如何快速補0 Array(len + 1).join('0')
let x = 998, //指定值
       x_2 = x.toString(2),
       len = 32 - x_2.length; // 須要補0的個數
    
    x_2 += Array(len + 1).join('0');

完整解題以下:function

function int32ToIp(int32){
    let int2 = int32.toString(2),
        len = 32 - int2.length,
        begins = [0,8,16,24],
        ipArr = [];

    if (len) {
        int2 += Array(len + 1).join('0')
    }

    begins.forEach((begin) => {
        ipArr.push(Number.parseInt(int2.slice(begin,begin + 8),2))
    })

    return ipArr.join('.');
}

int32ToIp(2149583361) // '128.32.10.1'

提交以後發現其餘大佬的簡潔思路是使用 位移運算符class

let x = 2149583361; // 按位移動會先將操做數轉換爲大端字節序順序(big-endian order)的32位整數
    x >> 24 & 0xff // 128 //右移24位便可獲得原來最左邊8位,而後&運算取值

同理右移1六、八、0便可取到對應的IP字段。二進制

函數以下:

function int32ToIp(int32){
    return `${int32 >> 24 & 0xff}.${int32 >> 16 & 0xff}.${int32 >> 8 & 0xff}.${int32 >> 0 & 0xff}`
}

int32ToIp(2149583361) // '128.32.10.1'
相關文章
相關標籤/搜索