Skip to content

Instantly share code, notes, and snippets.

@oharsta
Last active August 29, 2015 14:07
Show Gist options
  • Save oharsta/4f5a9f01cfebafc6d35f to your computer and use it in GitHub Desktop.
Save oharsta/4f5a9f01cfebafc6d35f to your computer and use it in GitHub Desktop.
Calculate the addition of IPv4 and IPv6 prefix lengths (e.g. a IPv4 /23 and a /23 result in a /22)
object PrefixCalculator {
def sumIpv4(ipv4Prefixes: Seq[Int]) : Int = doSumIpvX(ipv4Prefixes, 32)
def sumIpv6(ipv6Prefixes: Seq[Int]) : Int = doSumIpvX(ipv6Prefixes, 128)
private def doSumIpvX(prefixes: Seq[Int], bitSize: Int) : Int = {
val addressSize = prefixes.map(prefix => Math.pow(2, bitSize - prefix)).sum
(bitSize - (Math.log(addressSize) / Math.log(2))).floor.toInt
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment