比这篇新的文章: 生成四位不重复数字(0-9)的所有组合
比这篇旧的文章: 猜数字游戏的八步以内求解程序

python.普通 IP 转换为十进制 IP

语言: Python, 标签: IP 十进制 2008/06/22发布 1年前更新
作者: jfxwc, 点击2047次, 评论(10), 收藏者(0), , 打分:

背景
主题: 字体:
01 #encoding=utf-8
02 #IP To Decimal
03
04 #This IP is : g.cn
05 IP = '203.208.33.100'
06
07 IP1 = IP.split('.')[0]
08 IP2 = IP.split('.')[1]
09 IP3 = IP.split('.')[2]
10 IP4 = IP.split('.')[3]
11
12 print 'Your IP is : ' + IP
13 print '------------------------------------------------------------'
14 print 'Your Decimal IP is : ' + \
15         str(int(IP1)*256**3 + \
16             int(IP2)*256**2 + \
17             int(IP3)*256 + \
18             int(IP4))


所有评论,共10条:( 我也来说两句)

1
0
0
只调用一次split就行了,不过但就这个程序来说没多大关系
2
jfxwc 1年前 回复
0
0
呵呵,这个程序是好玩而已,是看见中国建设10进制网络有感而写。

不过老实说,我不会只用一次 split ,所以才这样写,不过觉得也比较好看,半瓶墨水兄还请指教一下。谢谢
3
0
0
@2: split的结果记录下来比如a = IP.split('.'),然后a[0], a[1], a[2], a[3]不就行了。
4
jfxwc 1年前 回复
0
0
呵呵,多谢半瓶墨水兄指教。现在明白了。
5
zsp007 1年前 回复
0
0

def ip2int(ip):
   return sum(
       int(i)*(256**pos)
       for pos,i in enumerate(reversed( ip.split('.') ) )
   )  

print ip2int('203.208.33.100')
啊,  注:为了减少spam,不含中文视为无效评论
6
zsp007 1年前 回复
0
0

def ip2int(ip):
   return sum(
       int(i)<<(pos<<3)
       for pos,i in enumerate(reversed( ip.split('.') ) )
   )

print ip2int('203.208.33.100')
我们要写大家看不懂的代码 ....
7
zsp007 1年前 回复
0
0
def ip2chr(ip):
   return "".join( chr(int(i)) for i in ip.split('.') )
其实我想要这个,方便在字符串做key的btree Tokyo Cabinet 数据库中查找
8
0
0
@7: 呵呵不错的想法
9
jfxwc 1年前 回复
0
0
还真是一眼看不懂 zsp007 的代码    
10
metal 2个月前 回复
0
0
我们要写大家看不懂的代码
(lambda x: reduce(lambda a, b: (a<<8)+b, reversed(map(int, x.split('.')))))('127.0.0.1')

发表评论

注册登录后再发表评论