[Tutor] Convert an IP address from binary to decimal

Steven D'Aprano steve at pearwood.info
Tue Jan 18 16:21:56 CET 2011


Tom Lin wrote:

> But one precondition is not to use int(string, base). How would you
> implement the conversion?

It's not hard. You have two choices: each character of the string
represents a bit, and should be either a "0" or a "1" (anything else is
an error). In which case its numeric value is either 0 or 1.

if bit == '0': value = 0
elif bit == '1': value = 1
else: raise ValueError("not a binary IP address")

If you are allowed to assume that the characters will only by 0 or 1,
and that there will never be anything else, you can do something even
smarter and faster. Here's a clue:

>>> total = 0
>>> s = "abaa"
>>> for c in s:
...     total += (c == "a")
...
>>> total
3

The boolean flags True and False are actually disguised numbers with
values 1 and 0.



-- 
Steven



More information about the Tutor mailing list