如何在Python中打包任意位序列? [英] How to pack arbitrary bit sequence in Python?

查看:129
本文介绍了如何在Python中打包任意位序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些二进制图像数据编码/压缩为序列(如果有位). (通常,此序列的长度不能完全符合整数的标准整数类型.)

I want to encode/compress some binary image data as a sequence if bits. (This sequence will, in general, have a length that does not fit neatly in a whole number of standard integer types.)

如何在不浪费空间的情况下做到这一点? (我意识到,除非位序列的长度为"nice",否则在末尾总是必须有少量[<1个字节]的剩余空间.)

How can I do this without wasting space? (I realize that, unless the sequence of bits has a "nice" length, there will always have to be a small amount [< 1 byte] of leftover space at the very end.)

FWIW,我估计每个要编码的符号最多需要3位. Python是否有用于此类工作的内置工具?

FWIW, I estimate that, at most, 3 bits will be needed per symbol that I want to encode. Does Python have any built-in tools for this kind of work?

推荐答案

虽然内置的内容并不十分方便,但是有第三方模块,例如 bitstring bitarray 就是为此而设计的.

There's nothing very convenient built in but there are third-party modules such as bitstring and bitarray which are designed for this.

from bitstring import BitArray
s = BitArray('0b11011')
s += '0b100'
s += 'uint:5=9'
s += [0, 1, 1, 0, 1]
...
s.tobytes()

要结合使用3位数字(即范围0-> 7),您可以使用

To join together a sequence of 3-bit numbers (i.e. range 0->7) you could use

>>> symbols = [0, 4, 5, 3, 1, 1, 7, 6, 5, 2, 6, 2]
>>> BitArray().join(BitArray(uint=x, length=3) for x in symbols)
BitArray('0x12b27eab2')
>>> _.tobytes()
'\x12\xb2~\xab '

一些相关问题:

  • What is the best way to do Bit Field manipulation in Python?
  • Python Bitstream implementations

这篇关于如何在Python中打包任意位序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆