[Tutor] Convert an IP address from binary to decimal

Steven D'Aprano steve at pearwood.info
Tue Jan 18 15:01:11 CET 2011


Tom Lin wrote:
> Hi guys,
> 
> Please help me with this:

We don't do homework. We'll give you some hints but not do the work.

> 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))

The question does not say "Search a string for zero or more IP addresses
in binary and convert them all". It says to convert an IP address
written in binary to dotted format. So throw away the regular
expression. It's wrong anyway: it would accept input like this:

"9999xxxxxxxx1234"

and try to convert that to an IP address.


Think about the problem you have. You are given as input a string of 32
0 or 1 characters. Anything else is an error -- there is no need to go
searching through a string looking for sequences of digits.

Once you have 32 characters, you can split it into four lots of eight
characters. How? Not with a regular expression!!! That is like using a
sledge-hammer to crack a peanut. Use slicing:


>>> s = "00001111" + "x"*24
>>> s
'00001111xxxxxxxxxxxxxxxxxxxxxxxx'
>>> s[0:8]
'00001111'


So you can take one 32-character string and slice it into four
8-character strings. Then *each* of the substrings can be converted from
binary into decimal. If you find a character other than 0 or 1, stop
immediately and raise an exception.

In pseudo-code:

Is the string exactly 32 characters? If not, then FAIL.
Split the string into four groups of eight.
For each group of eight, convert from binary to decimal. If you find
something other than 0 or 1, then FAIL.
Join the four groups with dots.


-- 
Steven


More information about the Tutor mailing list