質問

UDP 経由で MPEG Transport Stream プロトコルを読んでいますが、その中にいくつかのおかしなビットフィールド (たとえば長さ 13) が含まれています。「構造体」ライブラリを使用して広範な解凍を行っていますが、ビット操作を手動で調整するのではなく、「次の 13 ビットを取得する」という簡単な方法はありますか?C でビット フィールドを実行する方法のようなものが (C に戻らなくても) 欲しいと思っています。

提案はありますか?

役に立ちましたか?

解決

よくある質問です。あるよ ASPN クックブック 過去に私に役立ったエントリ。

そして、 これを実行するモジュールから 1 人が確認したい要件の広範なページ。

他のヒント

ビット文字列 モジュールはまさにこの問題に対処するように設計されています。これにより、ビットを基本構成要素として使用して、データの読み取り、変更、構築が可能になります。最新バージョンは 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()

完全なドキュメントは次のとおりです ここ.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top