题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
n1 = input() # ip地址 n2 = int(input()) # 整数 # 10进制转二级制,仅限8位数,返回字符串 def int_bin_1(n): b = "" for i in range(7,-1,-1): if n >= 2**i: n -= 2**i b += "1" else: b += "0" return b # 10进制转二进制,仅限32位数,返回字符串 def int_bin_2(n): b = "" for i in range(31,-1,-1): if n >= 2**i: n -= 2**i b += "1" else: b += "0" return b # 二进制转10进制,不限位数 def bin_int(s): n = 0 a = len(s)-1 for i in s: n += int(i) * (2**a) a -= 1 return n # 1. IP转整数 n1_list = n1.split(".") b1 = "" for i in n1_list: num = int(i) b1 += int_bin_1(num) print(bin_int(b1)) # 2. 整数转IP s = int_bin_2(n2) s1 = bin_int(str(s[0:8])) s2 = bin_int(str(s[8:16])) s3 = bin_int(str(s[16:24])) s4 = bin_int(str(s[24:32])) print(f"{s1}.{s2}.{s3}.{s4}")