Unpacking binary files
<p>I have to read a binary file. So I have totally immersed myself in the python <code>struct</code> module.
However there are still things that confuse me. Let's consider the following chunk of code:</p>

<pre><code>import struct

print struct.pack('5c', *'Hello')
to_pack = (5.9, 14.87, 'HEAD', 32321, 238, 99)
packed = struct.pack('2f4s3i', *to_pack)
print "packed: ", packed
</code></pre>

<p>output: </p>

<pre><code>Hello
packed:  �̼@��mAHEADA~�
</code></pre>

<p>I packed successively 2 floats, a 4 chars string, and three integers.
Then when unpacking: </p>

<pre><code>unpacked = struct.unpack('2f4s3i', packed)
print "unpacked: ", unpacked
</code></pre>

<p>Output: </p>

<pre><code> unpacked:  (5.900000095367432, 14.869999885559082, 'HEAD', 32321, 238, 99)
</code></pre>

<p>So the packing function turned my original data into binary data, whilst unpacking did the
opposite. However, does it mean I necessarily have to know how my data is organized, do I 
necessarily have to know which types are encoded, and their respective order?
What if I don't, how could I guess the right type order of my data? For instance if I do:</p>

<pre><code>unpacked = struct.unpack('2f4s3h', packed)  # I replaced the 3i with 3h 
print "unpacked: ", unpacked
</code></pre>

<p>I would get a nice error:</p>

<pre><code>unpacked = struct.unpack('2f4s3h', packed)
struct.error: unpack requires a string argument of length 18
</code></pre>

<p>So it seems to me that whatever the binary data I get when reading a binary file, if 
I don't know the correct types in the right order, I could not convert it to its original
form.</p>

<p>Is there a way to convert the data back to non-binary without specifying the expected types,
or would I really be stuck with a non-usable binary file?</p>

<p>I mean, even among those creating huge binary files from gigantic ones, how woud they
manage to retrieve their data successfully?</p>

<p>For information, my example was taken from this pdf file: <a href="https://gebloggendings.files.wordpress.com/2012/07/struct.pdf" rel="nofollow">https://gebloggendings.files.wordpress.com/2012/07/struct.pdf</a></p>