题解 | #整数与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
全部评论

相关推荐

07-03 16:02
门头沟学院 Java
点赞 评论 收藏
分享
北漂的牛马人:211佬,包进的,可能是系统问题
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 17:10
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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