题解 | 整数与IP地址间的转换

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // 将IP地址转换为长整数
    function ipToLong(ip) {
        const parts = ip.split(".").map(Number);
        return (
            (BigInt(parts[0]) << 24n) |
            (BigInt(parts[1]) << 16n) |
            (BigInt(parts[2]) << 8n) |
            BigInt(parts[3])
        );
    }

    // 将长整数转换为IP地址
    function longToIp(long) {
        const part1 = Number((long >> 24n) & 0xffn);
        const part2 = Number((long >> 16n) & 0xffn);
        const part3 = Number((long >> 8n) & 0xffn);
        const part4 = Number(long & 0xffn);
        return `${part1}.${part2}.${part3}.${part4}`;
    }
    let input1 = await readline();
    let input2 = await readline();
    console.log(ipToLong(input1).toString());
    console.log(longToIp(BigInt(input2)));
})();

全部评论

相关推荐

05-12 14:48
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务