unpacking data created by a machine with a 30-bit word
Constraints: Pure Python 2.6 or 2.7 + standard library. Solution either has to exist already or be pretty simple to implement (I have 3 days max, but it would be better to do it in 1-2). Has to be able to handle a throughput of ~3KB/s.
The problem: I'm getting a stream of packed data apparently created on a machine with a 30-bit word ("The formats...consist of 8 words, each containing 30 bits"). For instance, here's the first 5 fields:
A: bits 1-13
B: bits 14-17
C: bits 18-26
D: bits 27-30
E: bits 31-34
...
You see fields are falling across what would normally be considered byte boundaries. It gets worse farther on, for a total of 240 bits. This makes using struct.unpack() or ctypes an issue. Even if you turn on the _pack_ feature, you can't have a bitfield fall across a word boundary.
What I'd love to do is just read the entire 240 bits into a long binary buffer and mask out the exact bits I want. There doesn't seem to be such a data structure in Python 2.x (or 3.x?).
My next idea is to simulate the above. Put the 240 bits into a string. Select a chunk of bytes that contain those bits. Use struct.unpack() to read the bytes and then create a mask to get just those bits. Some shifting involved there. It's hairy and hasn't worked yet after a couple hours of work.
Better ideas?
Posted Aug 7, 2018, 11:14 AM UTC · edited
https://github.com/eerimoq/bitstruct
I see that it says the word "bits" on that page, but I don't see any evidence in the docs or the code that it actually will handle this. Can I read out just 3 bits in the middle of nowhere?
If you've got 240 bits and wanted 3 bits starting after the 27th bit, you'd just do something like:
Thanks, I'll check it out.
moments later O.M.G. This seems to be exactly what I want. Thanks a trillion!