Skip to content

Instantly share code, notes, and snippets.

@kjseefried
Created July 15, 2014 01:09
Show Gist options
  • Save kjseefried/ddf59759e63333f5258d to your computer and use it in GitHub Desktop.
Save kjseefried/ddf59759e63333f5258d to your computer and use it in GitHub Desktop.
Example of using Python bitstring
from bitstring import ConstBitArray, BitStream
# Opening from a file means that it won't be all read into memory
s = ConstBitArray(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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment