Tuesday, February 7, 2012

Translate a quad-dotted decimal netmask to its bit length equivalent

Here's an elegant way of translating a subnet netmask from its quad-dotted decimal representation to a bit length. The initial netmask is represented as a Python list. To get from the string representation to the list just do:

>>> b = "255.255.248.0".split(".")


to get the bitcount just do:

>>> reduce(lambda x, y: x + (y + 1)/32, b, 0)
23


 Modify to taste and njoy