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

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

语言: Python, 标签: IP 十进制 2008/06/22发布 6个月前更新
作者: jfxwc, 点击765次, 评论(9), 收藏者(0)

开关行号, 全选(Ctrl+C复制) | 一键复制:HTML, BBCode(Discuz!) , 源代码 | 查看:裸代码, 全屏
背景
主题: 字体:
Python语言: python.普通 IP 转换为十进制 IP
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))
打分:

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

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

不过老实说,我不会只用一次 split ,所以才这样写,不过觉得也比较好看,半瓶墨水兄还请指教一下。谢谢
3
半瓶墨水 6个月前 回复
0
0
@2: split的结果记录下来比如a = IP.split('.'),然后a[0], a[1], a[2], a[3]不就行了。
4
jfxwc 6个月前 回复
0
0
呵呵,多谢半瓶墨水兄指教。现在明白了。
5
zsp007 22天前 回复
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 22天前 回复
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 22天前 回复
0
0
def ip2chr(ip):
    return "".join( chr(int(i)) for i in ip.split('.') )
其实我想要这个,方便在字符串做key的btree Tokyo Cabinet 数据库中查找
8
半瓶墨水 22天前 回复
0
0
@7: 呵呵不错的想法
9
jfxwc 16天前 回复
0
0
还真是一眼看不懂 zsp007 的代码     

发表评论

注册登录后再发表评论