On 18/01/2011 14:45, Tom Lin wrote: > 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 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >
If I knew the input to be perfect it would be a simple matter '.'.join((str(int(input_ip[x:x+8], 2)) for x in range(4))) -- Kind Regards, Christian Witts _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor