Read my first binary file!

Wow.  I am shocked that this worked on the first try.  I created a script to read some of the header information from an S7K file.  One thing that got me stuck for a bit was the fact that the byte order used is little-endian.  Turns out this is no big deal.  I just had to end things with ‘le’, for example s.uintle instead of s.uint.

So here’s my first ever script to read binary data:

[sourcecode language=”python”]
#!usr/bin/env Python

# Purpose: to read the header of an s7k file
# Creator: Michelle

from bitstring import *

s = BitString(filename=’sample.s7k’) # Read in the file sample.s7k, and create a BitString object from it
print s.pos #Print the position in the file.  For fun.

protocolversion = s.readbytes(2).uintle
offset = s.readbytes(2).uintle
syncpat = s.readbytes(4).uintle
size = s.readbytes(4).uintle
print size

odof = s.readbytes(4).uintle
odid = s.readbytes(4).uintle

year = s.readbytes(2).uintle
day = s.readbytes(2).uintle
seconds = s.readbytes(4).floatle
hours = s.readbytes(1).uintle
minutes = s.readbytes(1).uintle

print year,day,seconds,hours,minutes
[/sourcecode]

And the output of my first ever binary-data-reading script:

0
396
2009 353 55.1300010681 17 53

3 thoughts on “Read my first binary file!

  1. Sweet! I asked Kurt, and bitstring should default to whatever Endian your processor uses. So for you (assuming you are still on your powerPC), the default is Big Endian, so you must specify when you are reading/writing Little Endian. For me, on my Intel, it is the other way around.

    I am excited to see you learning Python the same time I am. Seems like we’ll be a good resource for each other.

    1. Yes! I love it!! It’s so much fun – but it takes me so long to do things that I could do in 5 minutes in Matlab, because I have to learn EVERY SINGLE little step… 🙂

  2. I have installed python 3.2.4.when I am using the code for reading .s7k files it is giving me error to bitstring function

Leave a Reply

Your email address will not be published. Required fields are marked *