[Tutor] Convert an IP address from binary to decimal

bob gailer bgailer at gmail.com
Tue Jan 18 13:48:53 CET 2011


On 1/18/2011 8:08 AM, Christian Witts wrote:
> 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 .
Christian: note rule 2!

>> 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
Tom:

What exactly do you mean by "ugly"?
>> and I wonder if there is a better way to do this.
What do you mean by "better"?

The algorithm you programmed is one good way to accomplish your result. 
The only problems I see are using re, ** and int() which are less 
efficient than other ways.

The best might be - use slicing to get the 8 "bit" substrings, == to 
test for "1" and bit shifting.

Start with 0, add1 if current bit == "1" and shift left.

Then try * 2 instead of shift left.

Run timing tests on the various approaches. Given that this is a very 
fast algorithm timing tests might not be useful.
>> 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)
>>
> 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)))
>


-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list