Using struct to read binary files

mercado at
Fri Nov 27 02:59:29 CET 2009


I am writing a Python program to read the Master Boot Record (MBR),
and I'm having trouble because I have no previous experience reading
binary files.

First off, I've written a binary file containing the MBR to disk using
the following command:
sudo dd if=/dev/sda of=/tmp/mbrcontent bs=1 count=512

Then I want to read the MBR file and parse out its information.  For
example, I know that bytes 454-457 contain the address of the first
sector of the first partition, and bytes 458-461 contain the number of
sectors in the first partition (see for more information
on the structure of the MBR).

So far what I have is this:

f = open("/tmp/mbrcontent", "rb")
contents =

firstSectorAddress = contents[454:458]
numSectors = contents[458:462]

On my machine, the bytes contained in firstSectorAddress are
"\x3F\x00\x00\x00", and the bytes contained in numSectors are
"\x20\x1F\x80\x01".  I know from doing a pen and paper calculation
that the first sector address is 63, and the number of sectors is
25,173,792 (the numbers are stored in little-endian format).

How do I figure that out programmatically?  I think that I can use
struct.unpack() to do this, but I'm not quite sure how to use it.

Can anybody help me out?  Thanks in advance.

More information about the Python-list mailing list