二進位和十進位相互轉換、位運算 記錄下在codewar上做的一個題目和收穫 128.32.10.1 == 10000000.00100000.00001010.00000001 Because the above IP address has 32 bits, we can represent it ...
二進位和十進位相互轉換、位運算
記錄下在codewar上做的一個題目和收穫
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"
自己的解題思路是將十進位的數轉為二進位(不足32位補0),然後依次取8位轉化為十進位的數字,再用.
連接即為IP。
裡面的幾個點記錄一下:
- 十進位轉換為二進位
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 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'
提交之後發現其他大佬的簡潔思路是使用 位移運算符
let x = 2149583361; // 按位移動會先將操作數轉換為大端位元組序順序(big-endian order)的32位整數
x >> 24 & 0xff // 128 //右移24位即可得到原來最左邊8位,然後&運算取值
同理右移16、8、0即可取到對應的IP欄位。
函數如下:
function int32ToIp(int32){
return `${int32 >> 24 & 0xff}.${int32 >> 16 & 0xff}.${int32 >> 8 & 0xff}.${int32 >> 0 & 0xff}`
}
int32ToIp(2149583361) // '128.32.10.1'