Binary handling

Miki Tebeka miki.tebeka at zoran.com
Mon May 17 11:19:15 EDT 2004


Hello Derfel,

> I have a file of binary data. I want to read this file and parse the data in 
> it. The format of the file is:
> 8 bits number of data pakets
> 6 bits offset
> 20 bits time
> 8 states
> 
> How can I read this fields in binary? I see the struct module and the 
> binascii, but I can't split the diferent fiels.
--- bitter.py ---
# Testing
'''
 >>> b = BitStream(chr(int("10111010", 2)))
 >>> b.get_bits(3)
5
 >>> b.get_bits(2)
3
 >>> b.get_bits(3)
2
 >>> b.get_bits(0)
0
 >>> b.get_bits(1)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/tmp/bitter.py", line 27, in get_bits
     raise EOFError
EOFError
'''

from array import array

class BitStream:
     '''Bit stream implementation'''
     def __init__(self, data):
         self.arr = array("c", data)
         self.bit = 0 # Current output bit

     def get_bits(self, count):
         '''Get `count' bits from stream'''
         if count == 0: # Nothing to get
             return 0

         if not self.arr: # EOF
             raise EOFError

         value = 0
         for c in range(count):
             if not self.arr: # EOF
                 raise EOFError
             value <<= 1
             shifted = ord(self.arr[0]) >> (8 - self.bit - 1)
             value |= (shifted & 1)
             self.bit += 1
             if self.bit == 8: # Get new byte
                 self.arr.pop(0)
                 self.bit = 0

         return value

def _test():
     from doctest import testmod
     import bitter

     testmod(bitter)

if __name__ == "__main__":
     _test()
--- bitter.py ---

HTH.
Miki



More information about the Python-list mailing list