IP排序程序

IP排序程序

iplist=['192.168.1.33','10.5.1.3','10.5.2.4','202.98.96.68','133.120.1.1','192.168.1.22']
def ip2int(s):
    l = [int(i) for i in s.split('.')]
    return (l[0] << 24) | (l[1] << 16) | (l[2] << 8 | l[3]
def int2ip(i):
    l = [i >> 24,(i >> 16) & 255,(i >> 8 & 255,i & 255]   
    return '.'.join([str(i) for i in l])
iplist = [ip2int(ip) for ip in iplist]
iplist.sort()
iplist = [int2ip(i) for i in iplist]
print iplist


刚刚学习python 在网上看到的例子,个人认为那两个方法是对IP进行10进制和32转换的,请高手给详细解释下,谢谢

ip地址为 a.b.c.d   (a,b,c,d均<256)
a<<24相当于a*2^24,也即 a*256^3
b<<16相当于a*2^16,也即 a*256^2
c<<8相当于a*2^8,也即 a*256
ip2int()返回整数 X=a*256^3 + b*256^2 + c*256 + d

i &255就是取整数i的二进制表示的后8位,等同于i % 256
X >> 24 = X/(256^3) = a
(X >> 16)&255 = (X/(256^2))%256 =b
(X >> 8 )&255 = (X/256)%256 =c
X & 255 = d