[python] Convert IPv4 subnet mask to CIDR representation

Take an example of this subnet mask which CIDR representation is 28. These are the methods to convert to CIDR representation without using any module.

  • Split the netmask by dots, so that each octet is in a list.
  • For each item in the list, use bin function to get the binary representation of each octet, remember to type cast each octet from string to int(), bin() can only accept int() object.
  • Then use str() function to convert the bin object in order to use count method, the count method is used to count the number of “1” in the binary.
  • Then sum up the number of “1”s in the list.
netmask = ""
list_mask = netmask.split(".")

The result after split is like this : [‘255’, ‘255’, ‘255’, ‘240’]

processing = list()
for octet in lst_mask:

The result of processing object is: [8, 8, 8, 4]

Then sum up the integers in the list.


The result is 28.

The entire code can be simplified with list comprehension like this:

sum([str(bin(int(octet))).count("1") for octet in netmask.split(".")])

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s