gpt4 book ai didi

python - 使用 Python 2.7.x 中的所有可打印字符对 IP 地址进行编码

转载 作者:行者123 更新时间:2023-12-03 00:22:32 25 4
gpt4 key购买 nike

我想使用所有可打印字符将 IP 地址编码为尽可能短的字符串。根据https://en.wikipedia.org/wiki/ASCII#Printable_characters这些是 20hex 到 7Ehex 的代码。

例如:

shorten("172.45.1.33") --> "^.1 9" maybe.

为了使解码变得容易,我还需要编码的长度始终相同。我还想避免使用空格字符,以便将来更容易解析。

How can one do this?

我正在寻找适用于 Python 2.7.x 的解决方案。

<小时/>

到目前为止,我尝试修改 Eloims 的答案以使其在 Python 2 中工作:

首先,我安装了 Python 2 的 ipaddress 向后移植 (https://pypi.python.org/pypi/ipaddress)。

#This is needed because ipaddress expects character strings and not byte strings for textual IP address representations 
from __future__ import unicode_literals
import ipaddress
import base64

#Taken from http://stackoverflow.com/a/20793663/2179021
def to_bytes(n, length, endianess='big'):
h = '%x' % n
s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
return s if endianess == 'big' else s[::-1]

def def encode(ip):
ip_as_integer = int(ipaddress.IPv4Address(ip))
ip_as_bytes = to_bytes(ip_as_integer, 4, endianess="big")
ip_base85 = base64.a85encode(ip_as_bytes)
return ip_base

print(encode("192.168.0.1"))

现在失败了,因为 base64 没有属性“a85encode”。

最佳答案

以二进制形式存储的 IP 为 4 个字节。

您可以使用 Base85 将其编码为 5 个可打印 ASCII 字符。

使用更多的可打印字符将无法进一步缩短结果字符串。

import ipaddress
import base64

def encode(ip):
ip_as_integer = int(ipaddress.IPv4Address(ip))
ip_as_bytes = ip_as_integer.to_bytes(4, byteorder="big")
ip_base85 = base64.a85encode(ip_as_bytes)
return ip_base85

print(encode("192.168.0.1"))

关于python - 使用 Python 2.7.x 中的所有可打印字符对 IP 地址进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com