用到int和bin函数,在10进制和2进制之间反复转换
def transfer_ip2num(ip):
ip_list = ip.split('.')
bin_str = ''
for x in ip_list:
bin_str += bin(int(x))[2:].rjust(8,'0')
return int('0b'+ bin_str, 2)
def transfer_num2ip(num):
result = ''
bin_str = bin(int(num))[2:].rjust(32,'0')
for idx in range(4):
result = result + str(int('0b' + bin_str[idx*8:idx*8+8], 2)) + '.'
return result[:-1]
if __name__ == '__main__':
while True:
try:
print(transfer_ip2num(input()))
print(transfer_num2ip(input()))
except EOFError: break