Using struct to read binary files

M

mercado

Hello,

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
http://en.wikipedia.org/wiki/Master_boot_record for more information
on the structure of the MBR).

So far what I have is this:

--------------------------------------------------------------------------------
f = open("/tmp/mbrcontent", "rb")
contents = f.read()
f.close()

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top