题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
二进制、十进制和字符串直接的相互倒换
def encrypt(ip):
digits = []
for i in ip.split("."):
b = bin(int(i))[2:]
while len(b) < 8:
b = "0{}".format(b)
digits.append(b)
print(int("".join(digits), 2))
def decrypt(number):
b = bin(int(number))[2:]
while len(b) < 32:
b = "0{}".format(b)
ip = []
for i in range(0, 32, 8):
ip.append(str(int(b[i:i+8], 2)))
print(".".join(ip))
encrypt(input())
decrypt(input())