I'm decoding a binary file byte-by-byte. No problem in reading variables that have a size which is a multiple of 8 bits, such as:
#encoder
bitstream.add(data_id, 16)
#decoder
data_id = struct.unpack('>H', in_file.read(2))[0]
What if the data I'm willing to decode isn't a multiple of 8 bits? For example, I add in the bitstream the following data:
#encoder
bitstream.add(F1, 1)
bitstream.add(F2, 1)
bitstream.add(F3, 1)
bitstream.add(F4, 1)
bitstream.add(F5, 1)
if (aflag):
bitstream.add(F6_a, 1)
bitstream.add(F7, 1)
else:
bitstream.add(F6_b, 1)
If the if evaluates to True I have to read 7 bits, otherwise I read 6 bits.
#decoder
# read 8 bits
data = struct.unpack('>B', in_file.read(1))[0]
F1 = data >> 7
F2 = data >> 6 & 0b01
F3 = data >> 5 & 0b001
F4 = data >> 4 & 0b0001
F5 = data >> 3 & 0b00001
if (aflag):
# first data block
F6_a = data >> 2 & 0b000001
F7 = data >> 1 & 0b1
else:
# second data block
F6_b = data >> 2 & 0b000001
In the first data block
case, I'm reading 7 bits and I have a spare 1.
In the second data block
case, I'm reading 6 bits and I have 2 spare bits. After these 8 bits, I have variables which all are multiple of 8 bits or groups of variables which together have size which is a multiple of 8 bits. So, I'm looking for a solution that does not imply to read all subsequent variables accounting for the spare bits.
In the first data block
case, how can I set the bitstream pointer to the 7th bit, so that I can read the following data as if there have no been spare bits in the previous read?