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.
In : netmask_to_cidr('255.255.255.0') Out: 24 In : In : netmask_to_cidr('255.255.255.255') Out: 32 In : netmask_to_cidr('255.255.255.128') Out: 25
Please be aware it assume you have a valid netmask as input.
You can also see it here