Python에서 비트 필드 조작을 수행하는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/39663

  •  09-06-2019
  •  | 
  •  

문제

UDP를 통해 일부 MPEG 전송 스트림 프로토콜을 읽고 있는데 그 안에 이상한 비트 필드(예: 길이 13)가 있습니다.광범위한 압축 해제를 수행하기 위해 "struct" 라이브러리를 사용하고 있지만 비트 조작을 손으로 조정하는 대신 "다음 13비트 가져오기"라고 말할 수 있는 간단한 방법이 있습니까?나는 C가 비트 필드를 수행하는 방식과 같은 것을 원합니다(C로 되돌릴 필요 없이).

제안?

도움이 되었습니까?

해결책

자주 묻는 질문입니다.거기에 ASPN 요리책 과거에 나에게 도움이 된 항목입니다.

그리고 거기에는 한 사람이 이 작업을 수행하는 모듈에서 보고 싶어하는 광범위한 요구 사항 페이지입니다.

다른 팁

그만큼 비트스트링 모듈은 바로 이 문제를 해결하도록 설계되었습니다.비트를 기본 구성 요소로 사용하여 데이터를 읽고 수정하고 구성할 수 있습니다.최신 버전은 Python 2.6 이상(Python 3 포함)용이지만 버전 1.0은 Python 2.4 및 2.5도 지원합니다.

관련된 예는 전송 스트림에서 모든 null 패킷을 제거하는 다음과 같습니다(아마도 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