base converter

Carel Fellinger cfelling at iae.nl
Thu Jun 14 11:37:03 EDT 2001


Jeroen Wolff <jwolff at knoware.nl> wrote:
...
> 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. 
...
> Maybe i'm on the wrong track to solve my problem.....

you might try:

import operator

address, mask = "192.168.2.1/24".split("/")
mask = 2 ** long(mask) - 1
octets = [long(x) for x in address.split(".")]
shifted_octets = [octet << shift for (octet,shift) in zip(octets, [24,16,8,0])]
address = reduce(operator.add, shifted_octets)
-- 
groetjes, carel



More information about the Python-list mailing list