[Tutor] Convert an IP address from binary to decimal

Tom Lin lintao.im at gmail.com
Tue Jan 18 13:45:44 CET 2011


Hi guys,

Please help me with this:
Convert an IP address from binary string to decimal format.There are
some preconditions:
1.IP address is in the form of '000010010....001100'.32 bits with no dot.
2.int(string, base) is not allowed, You have to implement the conversion .
3.Performance should be considered.

For example an IP address like '11111111111111111111111111111111 '
would be converted to '255.255.255.255'

That's how I implement it. But I think it looks ugly and I wonder if
there is a better way to do this.

import re
import sys

def convert(bin_ip):
patt = re.compile(r'\d{8}')
bin_list = patt.findall(str(bin_ip))

dec_list = []
for bin in bin_list:
sum = 0
i = 7
for n in bin:
if int(n):
sum = sum + 2**i
i = i - 1
dec_list.append(str(sum))

dec_ip = '.'.join(dec_list)
print dec_ip

if __name__ == '__main__':
bin_ip = sys.argv[1:]
convert(bin_ip)


Thanks in advance and excuse my poor English.


Best regards,
Tom
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110118/a6744273/attachment.html>


More information about the Tutor mailing list