子网掩码有两种格式,一种是 IPv4 地址式的:255.255.255.0 ,另一种是十进制整数的:24
今天突然想起来,以前做的子网转换的bash的脚本不能用了,正好现在在学python,看看python是怎么实现的!还是请教google大哥吧!放出google后,得到这样一个结果,原文地址:子网掩码格式转换:
# coding:utf-8
def exchange_mask(mask):
“””
转换子网掩码格式
“””
# 计算二进制字符串中 ’1′ 的个数
count_bit = lambda bin_str: len([i for i in bin_str if i==’1′])
# 分割字符串格式的子网掩码为四段列表
mask_splited = mask.split(‘.’)
# 转换各段子网掩码为二进制, 计算十进制
mask_count = [count_bit(bin(int(i))) for i in mask_splited]
return sum(mask_count)
if __name__ == ‘__main__’:
print exchange_mask(’255.255.0.0′)
该程序运行后提示bin没有定义,随后对代码进行修改,改后代码就可以正常工作了!这也算是比较简洁的了,代码如下:
#!/usr/bin/env python
# coding:utf-8
def exchange_mask(mask):
bin = lambda n : (n > 0) and (bin(n / 2) + str(n % 2)) or ”
count_bit = lambda bin_str: len([i for i in bin_str if i==’1′])
mask_splited = mask.split(‘.’)
mask_count = [count_bit(bin((int(i)))) for i in mask_splited]
return sum(mask_count)
if __name__ == ‘__main__’:
print exchange_mask(’255.255.0.0′)
# coding:utf-8
def exchange_mask(mask):
bin = lambda n : (n > 0) and (bin(n / 2) + str(n % 2)) or ”
count_bit = lambda bin_str: len([i for i in bin_str if i==’1′])
mask_splited = mask.split(‘.’)
mask_count = [count_bit(bin((int(i)))) for i in mask_splited]
return sum(mask_count)
if __name__ == ‘__main__’:
print exchange_mask(’255.255.0.0′)
转载请注明:爱开源 » python版子网掩码转换