Binary and decimal conversion, shift operation

Binary and decimal conversion, bit operations

Under Record on codewar do a topic and harvest

128.32.10.1 == 10000000.00100000.00001010.00000001

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

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

Example : 2149583361 ==> "128.32.10.1"

Their problem-solving idea is to decimal numbers into binary (0 up less than 32), and then successively taken into eight decimal number, then .the connection shall be the IP .

Record a few points inside it:

  • Decimal to binary numObj.toString([radix])radix can specify decimal, the default is 10
    let x = 2149583361;
    x.toString(2) //  "10000000001000000000101000000001"
  • Binary to decimal Number.parseInt(string[, radix])radix can specify decimal, the default is 10
   Number.parseInt("10000000001000000000101000000001",2) // 2149583361
  • When less than 32 how to quickly fill0 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');

Complete problem-solving as follows:

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'

After submitting the bigwigs find other simple idea is to use the shift operator

    let x = 2149583361; // 按位移动会先将操作数转换为大端字节序顺序(big-endian order)的32位整数
    x >> 24 & 0xff // 128 //右移24位即可得到原来最左边8位,然后&运算取值

Similarly 16,8,0 right to get to the corresponding IP field.

Function is as follows:

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

int32ToIp(2149583361) // '128.32.10.1'

Guess you like

Origin www.cnblogs.com/shapeY/p/11078240.html