题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
const sIp = await readline();
console.log(ipToInt(sIp));
const int = await readline();
console.log(intToIp(int));
})();
function intToIp(int) {
// 进进制串
let b = toB(int);
for (let i = 1, len = 32 - b.length; i <= len; i++) {
b = "0" + b;
}
// console.log(b);
const ip1 = b.substr(0, 8);
const ip2 = b.substr(8, 8);
const ip3 = b.substr(16, 8);
const ip4 = b.substr(24, 8);
// 转换成十进制
return `${toInt(ip1)}.${toInt(ip2)}.${toInt(ip3)}.${toInt(ip4)}`;
}
function ipToInt(ip) {
const arr = ip.split(".");
// 解析成二进制
const b = arr.map((num) => {
let s = toB(num);
for (let i = 1, len = 8 - s.length; i <= len; i++) {
s = "0" + s;
}
return s;
});
// 连接起来
const sTwo = b.join("");
return toInt(sTwo);
}
function toInt(sTwo) {
// console.log(sTwo);
// 转换成十进制
const total = sTwo
.split("")
.reverse()
.map((char, i) => {
return +char * 2 ** i;
})
.reduce((total, b) => {
return total + b;
}, 0);
return total;
}
// 转换成二进制字符串
function toB(num) {
const arr = [];
while (num > 1) {
arr.push(num % 2);
num = +Math.floor(num / 2);
}
arr.push(num);
return arr.reverse().join("");
}