题解 | #整数与IP地址间的转换#(4个注意点)
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#ip地址为10.0.3.193
#转换为二进制:00001010 00000000 00000011 11000001
#转换为十进制型的IP地址:167773121
input1 = input() #IP地址
input2 = input() #十进制的IP地址
str1 = input1.split('.')
newstr1 = []
for element in str1:
x = bin(int(element))
x = x[2:] #注意:去除'0b'前缀,得到纯二进制字符串【注意1】
while len(x) < 8:
x = '0' + x
newstr1.append(x)
newstring1 = ''.join(newstr1) #注意这个用法【注意2】
newlast1 = int(newstring1,2)
print(newlast1)
#step2
new2 = bin(int(input2))
new2 = new2[2:]
while len(new2) < 32:
new2 = '0' + new2
a1 = new2[0:8] #注意切片区间【注意3】
a2 = new2[8:16]
a3 = new2[16:24]
a4 = new2[24:32]
a1 = str(int(a1,2))
a2 = str(int(a2,2))
a3 = str(int(a3,2))
a4 = str(int(a4,2))
strlast = a1+'.'+a2+'.'+a3+'.'+a4 #这里注意,不能直接把数字加上去【注意4】
print(strlast)