Public
Edited
Jan 6, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function ip2int(ip) {
const octets = ip.split('.');
const intRepresentation = ((BigInt(octets[0]) << 24n) +
(BigInt(octets[1]) << 16n) +
(BigInt(octets[2]) << 8n) +
BigInt(octets[3]));
return Number(intRepresentation);
}
Insert cell
function int2ip(int) {
return `${int >>> 24}.${(int >>> 16) & 0xFF}.${(int >>> 8) & 0xFF}.${int & 0xFF}`;
}
Insert cell
Insert cell
function smallestCIDR2(ipAddresses) {
const ips = ipAddresses.map(ip2int);
const first = ips[0].toString(2);

let num_of_same_bytes = 32;
for (let i = 1; i < ips.length; i++) {
let cur = ips[i].toString(2)
for (let j = 0; j < num_of_same_bytes; j++) {
if (cur[j] == first[j]) {
continue;
}
num_of_same_bytes = j
}
}
return `cidr: ${normalizeCIDR (`${int2ip(ips[0])}/${num_of_same_bytes}`)}`;
}
Insert cell
function normalizeCIDR(cidr) {
const [ip, prefix] = cidr.split("/");
const binaryIP = ip.split(".").map(part => parseInt(part).toString(2).padStart(8, "0")).join("");
const binaryPrefix = parseInt(prefix);
const networkAddress = binaryIP.slice(0, binaryPrefix) + "0".repeat(32 - binaryPrefix);
const normalizedIP = networkAddress.match(/.{8}/g).map(part => parseInt(part, 2)).join(".");
return normalizedIP + "/" + binaryPrefix;
}
Insert cell
normalizeCIDR ('34.70.0.0/6')
Insert cell
int2ip(ip2int('192.168.3.1'))
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more