Binary file Pt 1 - Only reading some

Jared Grubb jared.grubb at gmail.com
Mon Feb 4 23:12:10 EST 2008


You should look into the struct module. For example, you could do the same
thing via (using the variable names you used before):
header_str = info.read(13)
a,b,c,d,e = struct.unpack("6s4sBBB", header_str)

After that, you will probably be able to get the integers by (doing it one
at a time... read'ing more than 2 bytes at a time and processing it all at
once is going to be more efficient, but this is the basic idea):

read_str = info.read(2)
val = struct.unpack("H", read_str)

Read up on the struct module and I think you'll see what you need to do.
(note that if you arent getting the right numbers for val, you will need to
specify whether the data is big-endian or little-endian.... if you dont know
what that means, you will find it on Wikipedia)

Jared


On 4 Feb 2008, at 19:51, Mastastealth wrote:

I'm trying to create a program to read a certain binary format. I have
the format's spec which goes something like:

First 6 bytes: String
Next 4 bytes: 3 digit number and a blank byte
---
Next byte: Height (Number up to 255)
Next byte: Width (Number up to 255)
Next byte: Number 0 - 5
Every 2 bytes after that: Supposedly a number 0000 - 0899?

Anyway, I'm able to do the first 2 objects fine:

a = info.read(6)
b = info.read(4)

Printing both gives me what I mentioned above, a string and a 3 digit
number with a space. However, as I continue, things get trickier.

c = info.read(1)
d = info.read(1)

Printing c and d in this case gives me a block in the SPE output, or
if I run in a DOS prompt, 2 funny symbols. How do I get an integer out
of this? I'll probably need help once I get to the "every 2 byte"
section, but that'll be a separate post.
-- 
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080204/b3bf49e9/attachment-0001.html>


More information about the Python-list mailing list