gpt4 book ai didi

python - 在只接受有效 UTF8 的系统上存储任意二进制数据

转载 作者:太空狗 更新时间:2023-10-30 01:15:00 25 4
gpt4 key购买 nike

我有任意二进制数据。我需要将它存储在需要有效 UTF8 的系统中。它永远不会被解释为文本,我只需要将它放在那里并能够检索它并重构我的二进制数据。

显然 base64 可以工作,但我不能有那么多的通货膨胀。

如何在 python 2.7 中轻松实现这一点?

最佳答案

您将使用 ASCII 字符来表达您的数据。使用 Base64 是最有效的方法(在 Python 标准库中可用),就使二进制数据适合可打印文本(也是 UTF-8 安全)而言。当然,它需要多 33% 的空间来表达相同的数据,但其他方法需要更多额外的空间。

您可以将此与压缩 结合使用以限制这将占用多少空间,但使压缩成为可选的(标记数据)并且仅在数据较小时才实际使用它.

import zlib
import base64

def pack_utf8_safe(data):
is_compressed = False
compressed = zlib.compress(data)
if len(compressed) < (len(data) - 1):
data = compressed
is_compressed = True
base64_encoded = base64.b64encode(data)
if is_compressed:
base64_encoded = '.' + base64_encoded
return base64_encoded

def unpack_utf8_safe(base64_encoded):
decompress = False
if base64_encoded.startswith('.'):
base64_encoded = base64_encoded[1:]
decompress = True
data = base64.b64decode(base64_encoded)
if decompress:
data = zlib.decompress(data)
return data

'.' 字符不是 Base64 字母的一部分,所以我在这里用它来标记压缩数据。

您可以进一步去除 Base64 编码数据末尾的 1 或 2 个 = 填充字符;这些可以在解码时重新添加(添加 '=' * (-len(encoded) * 4) 到最后),但我不确定这是否值得。

您可以通过切换到 Base85 encoding 来进一步节省开支,二进制数据的 4 比 5 比率 ASCII 安全编码,因此有 20% 的开销。对于 Python 2.7,这仅在外部库 (Python 3.4 added it to the base64 library) 中可用。您可以使用 python-mom project在 2.7 中:

from mom.codec import base85

并用 base85.b85encode()base85 替换所有 base64.b64encode()base64.b64decode() 调用.b85decode() 改为调用。

如果您 100% 确定路径上的任何内容都不会将您的数据视为文本(可能会更改行分隔符,或解释和更改其他控制代码),您还可以使用 Base128 编码,将开销减少到 14.3%(每 7 个字节 8 个字符)。但是,我不能为您推荐可通过 pip 安装的 Python 模块;有一个GitHub hosted module但我没有测试过。

关于python - 在只接受有效 UTF8 的系统上存储任意二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583468/

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