将这种形式的字符串转换为 IP 地址的最佳方法是什么: "0200A8C0"
。字符串中的“八位字节”顺序相反,即给定的示例字符串应生成 192.168.0.2
。
原文由 Matt Joiner 发布,翻译遵循 CC BY-SA 4.0 许可协议
将这种形式的字符串转换为 IP 地址的最佳方法是什么: "0200A8C0"
。字符串中的“八位字节”顺序相反,即给定的示例字符串应生成 192.168.0.2
。
原文由 Matt Joiner 发布,翻译遵循 CC BY-SA 4.0 许可协议
>>> s = "0200A8C0"
>>> bytes = ["".join(x) for x in zip(*[iter(s)]*2)]
>>> bytes
['02', '00', 'A8', 'C0']
>>> bytes = [int(x, 16) for x in bytes]
>>> bytes
[2, 0, 168, 192]
>>> print ".".join(str(x) for x in reversed(bytes))
192.168.0.2
它简短明了;将其包装在一个带有错误检查功能的函数中以满足您的需要。
方便的分组功能:
def group(iterable, n=2, missing=None, longest=True):
"""Group from a single iterable into groups of n.
Derived from http://bugs.python.org/issue1643
"""
if n < 1:
raise ValueError("invalid n")
args = (iter(iterable),) * n
if longest:
return itertools.izip_longest(*args, fillvalue=missing)
else:
return itertools.izip(*args)
def group_some(iterable, n=2):
"""Group from a single iterable into groups of at most n."""
if n < 1:
raise ValueError("invalid n")
iterable = iter(iterable)
while True:
L = list(itertools.islice(iterable, n))
if L:
yield L
else:
break
原文由 Roger Pate 发布,翻译遵循 CC BY-SA 2.5 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答864 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
网络地址操作由套接字模块提供。
您可以将十六进制字符串转换为
packed ip
使用struct.pack()
和小端,无符号长格式。