Python3 字符串ip与int整数值互转

  • Post author:
  • Post category:python



  • 字符串ip转为int型整数值:
def ip2int(ip: str) -> int:
    return sum(int(v) * 256 ** (3 - i) for i, v in enumerate(ip.split(".")))

  • int型整数值转为字符串ip:
def int2ip(number: int) -> str:
    result = []
    for i in range(4):
        number, mod = divmod(number, 256)
        result.insert(0, mod)
    return ".".join(str(i) for i in result)


例子:



版权声明:本文为weixin_42000303原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。