Binary handling

D

Derfel

Hello all,
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.

Thanks in advance
Regards
 
D

Diez B. Roggisch

Derfel said:
Hello all,
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.

You can use struct to create a long from your data and then work on that
with the usual bitwise operators for shift and boolean and so that you
extract the actual data. If the above is the entire spec, I see some
problems to get the alignment proper, but with a bit of shifting you should
be able to work around that.
 
M

Miki Tebeka

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
'''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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,197
Messages
2,571,041
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top