Skip to content

Instantly share code, notes, and snippets.

@naosim
Last active November 28, 2023 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naosim/3410fec3c19eee102f50038c59a1c10e to your computer and use it in GitHub Desktop.
Save naosim/3410fec3c19eee102f50038c59a1c10e to your computer and use it in GitHub Desktop.
ipv6
function getBitsAfter33(ipv6) {
function hexTo2Bits(v, bitLength = 4) {
if(v >= 10) {
v = "ABCDEF"[v - 10]
}
return (new Array(bitLength).fill("0").join("") + parseInt(v, 16).toString(2)).slice(-bitLength);
}
function bit2toHex(num) {
var p = num.split("").reverse().map((v, i) => Math.pow(2, i) * parseInt(v)).reduce((memo, v) => memo + v, 0);
if(p < 10) {
return "" + p
} else {
return "ABCDEF"[p - 10]
}
}
var [body, tail] = ipv6.split("::/");
const fixedBit = parseInt(tail) - 32;
const variableBit = 4 - fixedBit;
if(fixedBit < 0 || fixedBit > 4) {
throw new Error("大きすぎ");
}
if(fixedBit == 0) {
return;
}
var seg = body.split(":")[2];
var value = "0000";
if(seg) {
value = hexTo2Bits(seg[0]);
}
const fixed = value.slice(0, fixedBit);
var result = "";
for(let i = 0; i < Math.pow(2, variableBit); i++) {
var p = fixed + hexTo2Bits(i, variableBit);
// console.log(p, bit2toHex(p));
result += bit2toHex(p);
// console.log(i, fixed + hexTo2Bits(i, variableBit));
}
return `[${result}]`;
}
function convert(ipv6) {
return [...ipv6.split(":").slice(0, 2), getBitsAfter33(ipv6)].filter(v =>v).join(":")
}
console.log(convert("0000:0000:8000::/32"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment