ip与数字之间的转换

273 阅读1分钟

1. 题目

www.nowcoder.com/practice/66…

2. 考点

  1. 进制转换 二进制与十进制 相互转换 可使用函数bin() int(x,base=2) 可手写进制转换函数
  2. 字符串的切割以及缺失填补。

3. 解析

  1. 分析字符串的规律 都使用八位进行存储。
  2. 字符与数字之间的相互转换。
  3. 采用bin() int()函数进行解析进制。
  4. 字符串拼接时需要考虑好长度
  5. hc(x) 可使用 bin(x)[2:]进行替换

4. 核心代码

# 10.0.3.193  167773121
# 167969729 10.3.3.193


def hc(d: int):
    ret = []
    while True:
        n = d % 2
        ret.insert(0, str(n))
        if d == 0: break
        d //= 2
    return ret


def to_ip_int(i: str):
    i_list = [int(j) for j in i.split('.')]
    result = []
    for j in i_list:
        h = hc(j)
        tmp = "0" * (8 - len(h)) + "".join(h) if len(h) < 8 else "".join(h[-8:])
        result.append(tmp)
    return int("".join(result), base=2)


def to_ip_str(i: int):
    h = hc(i)
    result = "0" * (8 * 4 - len(h)) + "".join(h) if len(h) < 32 else "".join(h[-8 * 4:])
    result = [str(int(result[i:i + 8], base=2)) for i in range(0, len(result), 8)]
    return ".".join(result)


def bp(i):
    if isinstance(i, str):
        return to_ip_int(i)
    if isinstance(i, int):
        return to_ip_str(i)


if __name__ == '__main__':
    while True:
        try:
            print(bp(input()))
            print(bp(int(input())))
        except EOFError:
            break