Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module for implementing binary file formats?

I frequently find myself needing to write code to interact with binary file formats for which there aren't existing tools. I'm looking for an easy way to implement readers/writers for structured binary formats -- ideally something that will let me create the reader using some sort of simple declarative format.

I've found the Construct module, which works but seems to have been largely abandoned by the author. I'm wondering if there are any alternatives out there that people have worked with.

like image 944
larsks Avatar asked Feb 20 '11 03:02

larsks


1 Answers

Personally I'd use the bitstring module, but I may be biased as I wrote it. There's some simple code for reading/writing a binary format in the manual as an example.

This is one way to create via a binary format:

fmt = 'sequence_header_code,
       uint:12=horizontal_size_value,
       uint:12=vertical_size_value,
       uint:4=aspect_ratio_information,
       ...
       '
d = {'sequence_header_code': '0x000001b3',
     'horizontal_size_value': 352,
     'vertical_size_value': 288,
     'aspect_ratio_information': 1,
     ...
    }

s = bitstring.pack(fmt, **d)

and one method to parse it afterwards:

>>> s.unpack('bytes:4, 2*uint:12, uint:4')
['\x00\x00\x01\xb3', 352, 288, 1]
like image 83
Scott Griffiths Avatar answered Oct 20 '22 00:10

Scott Griffiths