题解 | #整数与IP地址间的转换#python3 详解
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
1、二进制与十进制互相转换,bin('十进制数')为十进制转二进制,int('二进制数',2)为二进制转十进制
2、str.zifill方法向左自动补齐,记得先把二进制数前的'0b'去除
def iptoint(ip): l = list(map(lambda x:bin(int(x))[2:].zfill(8),ip.split('.'))) return int(''.join(l),2) def inttoip(num): s = bin(int(num))[2:].zfill(32) l = [str(int(s[i*8:i*8+8],2)) for i in range(4)] return '.'.join(l) while True: try: ip,num = input(),input() print(iptoint(ip)) print(inttoip(num)) except: break