Take an example of this subnet mask 255.255.255.240 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 = "255.255.255.240" list_mask = netmask.split(".")
The result after split is like this : [‘255’, ‘255’, ‘255’, ‘240’]
processing = list() for octet in lst_mask: processing.append(str(bin(int(octet))).count("1"))
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(".")])