Python—IP地址与整数之间的转换

python

1. 将整数转换成IP:

思路:将整数转换成无符号32位的二进制,再8位进行分割,每8位转换成十进制即可。

方法一:#!usr/bin/python

2 #encoding=utf-8

3 #1. 将整数转换成32位无符号二进制

4 def intToIp(num):

5 s = []

6 g = []

7 h = []

8 for i in range(32):

9 a = num%2

10 s.insert(0,a)

11 num = num/2

12 print s

13 #2. 每8位进行分割,将4个8位二进制转换成十进制,加.连接即可。

14 for i in xrange(0,32,8):

15 g.append(s[i:i+8])

16 print g

17 for temp in g:

18 sum = 0

19 j = 0

20 for temp2 in temp:

21 sum = sum + temp2*(2**(7-j))

22 j += 1

23 print sum

24 h.append(str(sum))

25 return '.'.join(h)

26 a=intToIp(123456789)

27 print a


方法二:

 1 #!usr/bin/python

2 #encoding=utf-8

3 def inttoip(num):

4 s = bin(num)[2:]

5 s = s.zfill(32)

6 g = []

7 h = []

8 for i in xrange(0,32,8):

9 g.append(s[i:i+8])

10 for temp in g:

11 h.append(str(int(temp,2)))

12 e = ".".join(h)

13 print e

14

15 inttoip(123456789)

2. 将IP地址转换成整数:

思路:将IP的四位分别转换成8位二进制,去"."后整合,再换算成十进制。

#!usr/bin/python

2 #encoding=utf-8

3 #将IP地址转换为数值字符串,如7.91.205.21转换后为“123456789”

5 def IpToInt(num):

6 #1.将IP地址转换成32位的二进制。

7 s = num.split('.')

8 h = []

9 g = []

10 for temp in s:

11 while(temp!=0):

12 temp = int (temp)

13 a = temp % 2

14 h.insert(0,a)

15 temp = temp/2

16 if len(h)!= 8:

17 for i in range(8-len(h)):

18 h.insert(0,0)

19 g.extend(h)

20 h = []

21 # print g

22 #2. 将二进制换算成整数:

23 sum = 0

24 j = 0

25 for temp2 in g:

26 sum = sum + temp2*(2**(31-j))

27 j += 1

28 print sum

29 IpToInt("7.91.205.21")

方法二:借助Python内置函数

1 #!usr/bin/python

2 #encoding=utf-8

3 def iptoint(num):

4 h=[]

5 s = num.split(".")

6 for temp in s:

7 a = bin(int(temp))[2:]

8 a = a.zfill(8)

9 h.append(a)

10 g = "".join(h)

11 e = int(g,2)

12 print e

13

14 iptoint('7.91.205.21')

注:初学python,代码有点low,请见谅!

以上是 Python—IP地址与整数之间的转换 的全部内容, 来源链接: utcz.com/z/389183.html

回到顶部