HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Decimal-to-binary converter for IP addresses

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
decimalbinaryforaddressesconverter

Problem

def dec_to_bin(ip):

    ip_array = ip.split(".")
    ip_array = filter(None, ip_array)

    if len(ip_array) != 4:
        return "Invalid IP Address format"

    else:
        ip_bin = []

        for x in range(len(ip_array)):

            # Formatting example referenced from: 
            # http://stackoverflow.com/a/10411108/1170681

            ip_bin.append('{0:08b}'.format(int(ip_array[x])))
            ip_bin.append(".")

        ip_bin.pop()
        return ''.join(ip_bin)


This is a simple parser that will take a IP address in decimal form and convert it into its binary representation.

I'm looking for any tips on coding styles and improving the efficiency of the code.

Solution

Code simplification and related:

Line 4: remove line 3 and replace line 4 with

ip_array = filter(None, ip.split('.'))


Line 7:
Create an exception, to prevent that a caller gets a string of error instead of the actual result.

Line 12: assuming this is not python3, it's better if you use xrange() instead of range(), because range would create an actual list listing all the items in specified range. xrange(), instead, returns the next item in the sequence without creating the list. This behaviour is the same as the range() function in python3.
Anyway, for your purposes changing it with:

for el in ip_array:
    ip_bin.append('{0:08b}'.format(int(el)))


or, even better:

ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]


Last line:
instead of appending the "." after each element, join over the dot:

return '.'.join(ip_bin)


Style:
Pursue consistency in all the code: if you use double-quotes for defining strings, use them everywhere, same thing with single-quotes (which i personally prefer for strings, reserving double ones for docstrings).

Reassuming:

def dec_to_bin(ip):

    ip_array = filter(None, ip.split('.'))

    if len(ip_array) != 4:
        raise NotValidIPException('Invalid IP Address format.')
    else:
        ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]
        return '.'.join(ip_bin)

Code Snippets

ip_array = filter(None, ip.split('.'))
for el in ip_array:
    ip_bin.append('{0:08b}'.format(int(el)))
ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]
return '.'.join(ip_bin)
def dec_to_bin(ip):

    ip_array = filter(None, ip.split('.'))

    if len(ip_array) != 4:
        raise NotValidIPException('Invalid IP Address format.')
    else:
        ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]
        return '.'.join(ip_bin)

Context

StackExchange Code Review Q#19388, answer score: 5

Revisions (0)

No revisions yet.