我正在尝试将最大可用主机地址'的数值转换为CIDR表示法IP,例如:192.168.1.1/28的可用主机空间为14.但是192.168.1.1/30和/ 31都有可用的主机2的空间,这是问题发挥作用的地方 . 以下代码显示了预期值和实际值:

let ip = "192.168.1.1";

    console.log("max hosts of 14, expected: 255.255.255.240, got: " + test(ip, 14));
        //the problem, these should give the correct result respectively
        console.log("max hosts of 2, expected: 255.255.255.254, got: " + test(ip, 2));
        console.log("max hosts of 2, expected: 255.255.255.252, got: " + test(ip, 2));

    let test = function(ip, maxHosts){
        let numericNetmask = (maxHosts ^ 0xFFFFFFFF) - 1;
        let str = [];
        for (let shift = 24; shift > 0; shift -= 8) {
            str.push(((numericNetmask >>> shift) & 0xFF).toString());
        }
        str.push((numericNetmask & 0xFF).toString());
        return str.join(".");
    };

当然,我当然明白在这种情况下将自己的最大主机转换回网络掩码是不可能的,但是,考虑到IP地址,这是否可能? (注意:这是classess supernetting) .

当然,在正常的用例中,例如,可以通过将CIDR网络掩码存储为值来“破解”这种形式,但我希望有一种替代方案 .