<p>I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C).</p>

<p>Suggestions?</p>

[{'answer_id': 39760, 'author': 'Thomas Vander Stichele', 'author_id': 2900, 'author_profile': 'https://Stackoverflow.com/users/2900', 'pm_score': 4, 'selected': True, 'text': '<p>It\'s an often-asked question.  There\'s an <a href="http://code.activestate.com/recipes/113799/" rel="noreferrer">ASPN Cookbook</a> entry on it that has served me in the past.</p>\n\n<p>And there is an <a href="http://wiki.python.org/moin/BitManipulation" rel="noreferrer">extensive page of requirements one person would like to see from a module doing this.</a></p>\n'}, {'answer_id': 1086668, 'author': 'Scott Griffiths', 'author_id': 87699, 'author_profile': 'https://Stackoverflow.com/users/87699', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="https://github.com/scott-griffiths/bitstring" rel="nofollow noreferrer">bitstring</a> module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well.</p>\n\n<p>A relevant example for you might be this, which strips out all the null packets from a transport stream (and quite possibly uses your 13 bit field?):</p>\n\n<pre><code>from bitstring import Bits, BitStream  \n\n# Opening from a file means that it won\'t be all read into memory\ns = Bits(filename=\'test.ts\')\noutfile = open(\'test_nonull.ts\', \'wb\')\n\n# Cut the stream into 188 byte packets\nfor packet in s.cut(188*8):\n    # Take a 13 bit slice and interpret as an unsigned integer\n    PID = packet[11:24].uint\n    # Write out the packet if the PID doesn\'t indicate a \'null\' packet\n    if PID != 8191:\n        # The \'bytes\' property converts back to a string.\n        outfile.write(packet.bytes)\n</code></pre>\n\n<p>Here\'s another example including reading from bitstreams:    </p>\n\n<pre><code># You can create from hex, binary, integers, strings, floats, files...\n# This has a hex code followed by two 12 bit integers\ns = BitStream(\'0x000001b3, uint:12=352, uint:12=288\')\n# Append some other bits\ns += \'0b11001, 0xff, int:5=-3\'\n# read back as 32 bits of hex, then two 12 bit unsigned integers\nstart_code, width, height = s.readlist(\'hex:32, 2*uint:12\')\n# Skip some bits then peek at next bit value\ns.pos += 4\nif s.peek(1):\n    flags = s.read(9)\n</code></pre>\n\n<p>You can use standard slice notation to slice, delete, reverse, overwrite, etc. at the bit level, and there are bit level find, replace, split etc. functions. Different endiannesses are also supported.</p>\n\n<pre><code># Replace every \'1\' bit by 3 bits\ns.replace(\'0b1\', \'0b001\')\n# Find all occurrences of a bit sequence\nbitposlist = list(s.findall(\'0b01000\'))\n# Reverse bits in place\ns.reverse()\n</code></pre>\n\n<p>The full documentation is <a href="https://bitstring.readthedocs.io/en/latest/" rel="nofollow noreferrer">here</a>.</p>\n'}]
['https://Stackoverflow.com/questions/39663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2587612/']