题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
while True:
try:
ip, long = input(), int(input())
# 将ip地址分段
nums = list(map(int, ip.split('.')))
# 将每段转换成8位二进制
res = ''
for n in nums:
temp = bin(n).replace('0b', '')
res += (8 - len(temp)) * '0' + temp # 不足8位向前补'0'
# 输出十进制整数
print(int(res, 2))
# 将十进制的IP地址转成二进制
bstr = bin(long).replace('0b', '')
bstr = (32 - len(bstr)) * '0' + bstr # 不足32位向前补'0'
lst = []
i = 0
while i + 8 <= len(bstr):
lst.append(bstr[i:i+8])
i += 8
# 输出IP地址
print('.'.join([str(int(x, 2)) for x in lst]))
except:
break