在Python中进行位域操作的最佳方法是什么?

问题描述 投票:25回答:2

我正在阅读一些基于UDP的MPEG传输流协议,并且其中包含一些时髦的位域(例如,长度为13)。我正在使用“结构”库进行广泛的解压缩,但是有一种简单的方式说“获取接下来的13位”,而不必手动调整位操作吗?我想要类似C处理位字段的方式(不必还原为C)。

建议?

python udp bits bit-fields
2个回答
8
投票

这是一个经常问的问题。过去曾为我提供过ASPN Cookbook条目。

并且有extensive page of requirements one person would like to see from a module doing this.


26
投票

bitstring模块旨在解决此问题。它使您可以使用位作为基本构建块来读取,修改和构造数据。最新版本适用于Python 2.6或更高版本(包括Python 3),但1.0版也支持Python 2.4和2.5。

与您相关的示例可能就是这个,它从传输流中剥离了所有空包(并且很可能使用您的13位字段?):

from bitstring import Bits, BitStream  

# Opening from a file means that it won't be all read into memory
s = Bits(filename='test.ts')
outfile = open('test_nonull.ts', 'wb')

# Cut the stream into 188 byte packets
for packet in s.cut(188*8):
    # Take a 13 bit slice and interpret as an unsigned integer
    PID = packet[11:24].uint
    # Write out the packet if the PID doesn't indicate a 'null' packet
    if PID != 8191:
        # The 'bytes' property converts back to a string.
        outfile.write(packet.bytes)

这里是另一个例子,包括从位流中读取:

# You can create from hex, binary, integers, strings, floats, files...
# This has a hex code followed by two 12 bit integers
s = BitStream('0x000001b3, uint:12=352, uint:12=288')
# Append some other bits
s += '0b11001, 0xff, int:5=-3'
# read back as 32 bits of hex, then two 12 bit unsigned integers
start_code, width, height = s.readlist('hex:32, 2*uint:12')
# Skip some bits then peek at next bit value
s.pos += 4
if s.peek(1):
    flags = s.read(9)

您可以使用标准的切片符号在位级别切片,删除,反向,覆盖等,并且具有位级别的查找,替换,分割等功能。还支持不同的字节序。

# Replace every '1' bit by 3 bits
s.replace('0b1', '0b001')
# Find all occurrences of a bit sequence
bitposlist = list(s.findall('0b01000'))
# Reverse bits in place
s.reverse()

完整的文档是here

© www.soinside.com 2019 - 2024. All rights reserved.