Last active
September 7, 2016 11:34
-
-
Save stelcheck/3fd2d5d073b0a30116b2acf570ae46a2 to your computer and use it in GitHub Desktop.
CIDR from netmask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hammingWeight(i) { | |
i = i - ((i >> 1) & 0x55555555); | |
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); | |
return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; | |
} | |
function netmaskToCIDR(netmask) { | |
let chunks = netmask.split('.') | |
if (chunks.length != 4) { | |
return false; | |
} | |
let lastChunk = 255 | |
let acc = 0 | |
for (let i = 0; i < 4; i += 1) { | |
let chunk = parseInt(chunks[i], 10) | |
if (isNaN(chunk)) { | |
return false | |
} | |
if (lastChunk < chunk) { | |
return false | |
} | |
if (chunk === 0 || chunk === 255 || chunk === 254 || chunk === 252 || chunk === 248 || chunk === 240 || chunk === 224 || chunk === 192 || chunk === 128) { | |
acc += hammingWeight(chunk) | |
lastChunk = chunk | |
} else { | |
return false | |
} | |
} | |
return acc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment