python - 整数列表二进制表示的文件压缩/解压缩
问题描述
目前,我有一个将整数列表转换为二进制表示的系统。我计算每个数字所需的字节数,然后使用该to_bytes()
函数将它们转换为字节,如下所示:
o = open(outFileName, "wb")
for n in result:
numBytes = math.ceil(n.bit_length()/8)
o.write(n.to_bytes(numBytes, 'little'))
o.close()
但是,由于字节的长度不同,允许解包程序/函数知道每个字节有多长的方法是什么?我听说过使用 struct 模块,特别是 pack 函数,但是考虑到效率和尽可能减小文件的大小,解决这个问题的最佳方法是允许这样的解包程序检索原始编码整数的确切列表?
解决方案
You can't. Your encoding maps different lists of integers to the same sequence of bytes. It is then impossible to know which one was the original input.
You need a different encoding.
Take a look at using the high bit each byte. There are other ways that might be better, depending on the distribution of your integers, such as Golomb coding.
推荐阅读
- c# - 使用 PlayerPrefs 的 Unity Highscore 不起作用
- php - 循环遍历日期数组并查找连续两天的集合并合并值
- python - 如何使用新的 discord.py 版本获取不和谐服务器中所有成员的列表?
- sql - 如何动态创建表?
- c# - 微服务架构如何使用identityserver4进行基于角色的授权?
- python - 为什么我在信息最丰富的功能上全都错了
- python - 如何在scrapy运行之前手动进行身份验证?
- hbase - 数据驻留在 HDFS(HFile) 上时的 HBase 读取性能如何
- react-native - React -native ScrollView 水平滚动冲突
- android - 应用程序关闭时,带有广播接收器的工作管理器不起作用