I have been having some real trouble with this for a while. I am receiving a string of binary data in python and I am having trouble unpacking and interpreting only a 5bit subset (not an entire byte) of the data. It seems like whatever method comes to mind just simply fails miserably.
Let’s say I have two bytes packed binary data, and I would like to interpret the first 10bits within the 16. How could I convert this to an 2 integers representing 5bits each?
Use bitmasks and bitshifting:
The trick here is to know that 31 is a 5-bit bitmask:
As you can see you could also just use the
0bbinary number literal notation if you find that easier to work with.See the Python Wiki on bit manipulation for more background info.