Using struct to read binary files

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Nov 26 22:22:37 EST 2009


En Thu, 26 Nov 2009 22:59:29 -0300, mercado <python.dev.9 at gmail.com>  
escribió:

> 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.

You're almost done:

py> import struct
py> firstSectorAddress = "\x3F\x00\x00\x00"
py> struct.unpack("<L", firstSectorAddress)
(63,)
py> struct.unpack("<L", "\x20\x1F\x80\x01")
(25173792,)

-- 
Gabriel Genellina




More information about the Python-list mailing list