base converter

Remco Gerlich scarblac at pino.selwerd.nl
Thu Jun 14 07:03:22 EDT 2001


Jeroen Wolff <jwolff at knoware.nl> wrote in comp.lang.python:
> On Wed, 13 Jun 2001 22:01:08 GMT, "Fredrik Lundh"
> <fredrik at pythonware.com> wrote:
> 
> >(why has decimal to binary conversion suddenly turned into a
> >FAQ the last few months?  it wasn't this way in the old days,
> >and I cannot remember ever having to output things as binary
> >numbers in a real-life project...  can anyone explain?)
> >
> ></F>
> >
> Me it is to convert an ip addresses like (192.168.2.1/24) into a 32
> bits integer. Also the mask i wil convert to a 32 bit interger. Via
> converting the 4 octets into its binary representation. Put all the 32
> bits in a string and convert it to a interger. After that i can do an
> AND between these two integers and calucate the network part of it.

socket.inet_aton gives the 32 bit network representation of an IP address.
It gives it as a string of 4 bytes though.

Then you could use struct.unpack to put it into an integer.

>>> struct.unpack(">i", socket.inet_aton("127.0.0.1"))[0]
2130706433

And use & to and them. Then pack, etc.

-- 
Remco Gerlich



More information about the Python-list mailing list