Skip to content

Read my first binary file!

December 22, 2009

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:

#!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

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

0
396
2009 353 55.1300010681 17 53
Advertisements
2 Comments leave one →
  1. Monica permalink
    January 19, 2010 7:00 am

    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.

    • michellejw permalink*
      January 19, 2010 7:03 am

      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… 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: