Converting a netmask to CIDR with vanilla python

On a quick note:

I wasn’t able to find a simple solution to convert a classicly formated netmask to a CIDR format in python. So I wrote this line:

sum([ bin(int(bits)).count("1") for bits in m_netmask.split(".") ])

Place into a function:

def netmask_to_cidr(m_netmask):
  return(sum([ bin(int(bits)).count("1") for bits in m_netmask.split(".") ]))

It takes a netmask as a string (for example 255.255.255.0) and will convert it into a binary representation, then it will count the ones in it. Subsequently it computes the sum of the count result. Very simple.

Some examples:

In [79]: netmask_to_cidr('255.255.255.0')
Out[79]: 24

In [80]:                                                                                                                                                      
                                                                                                                                                              
In [80]: netmask_to_cidr('255.255.255.255')                                                                                                                   
Out[80]: 32                                                                                                                                                   
                                                                                                                                                              
In [81]: netmask_to_cidr('255.255.255.128')                                                                                                                   
Out[81]: 25 

Please be aware it assume you have a valid netmask as input.

You can also see it here

have fun!