题解 | 整数与IP地址间的转换

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

ip_list = list(map(int, input().split('.')))
ip_10 = int(input())

ip_10_list = []    # 将IP地址转化为32位的二进制数
for i in ip_list:
    ip_10_list.append(f'{i:0{8}b}')    # f-string转化十进制数为8位二进制,不够的补0
ip_10_str = ''.join(ip_10_list)
ip_10_str = ip_10_str[::-1]    # 倒序输出

sums = 0    # 计算32为二进制数是十进制的多少
for i in range(len(ip_10_str)):
    sums += int(ip_10_str[i]) * 2 ** i

ip_2_str = f'{ip_10:0{32}b}'    # 将十进制数转化为32位二进制数并切片
ip_2_str1 = ip_2_str[0:8]
ip_2_str2 = ip_2_str[8:16]
ip_2_str3 = ip_2_str[16:24]
ip_2_str4 = ip_2_str[24:32]
ip_10_str1 = int(ip_2_str1, 2)    # 转化十进制
ip_10_str2 = int(ip_2_str2, 2)
ip_10_str3 = int(ip_2_str3, 2)
ip_10_str4 = int(ip_2_str4, 2)

print(sums)
print(f'{ip_10_str1}.{ip_10_str2}.{ip_10_str3}.{ip_10_str4}')

全部评论

相关推荐

点赞 评论 收藏
分享
2025-12-24 13:37
已编辑
浙江农林大学 C++
Eryi_是不是名字...:金牌哥,你这要是考研C9进复试线乱杀啊。可以试试字节腾讯华子,我感觉投华子实习概率很大啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务