Reading a binary file

Axel Bock news-and-lists at the-me.de
Thu Jun 26 11:19:43 EDT 2003


Am Thu, 26 Jun 2003 16:14:58 +0200 schrieb Sorin Marti:

> This is what I have done. Now I have a file (called cpu1db2.dat) and
> this file has a length of 16 bytes.
> 
> Byte Number/Length   Type       Hex-Value
> ---------------------------------------------------------------- 
> [... content description ...]
> So I have written a python class which makes a connection to the
> [... lots of strange calculation ...]
> 10000101 = 133dec. Now you take away 127 from 133 then you get six,
> thats the exponent. The rest (110010000000000000000000) has a hex value
> of C80000 this is 13107200 decimal. Now you have to multiply 13107200
> with 2^6 and 2^-23 and you get (tataaaaaa!): 100!

whew. I don't get it, but anyways I think I can be useful ;-)

look at the struct-module: "This module performs conversions between
Python values and C structs represented as Python strings. It uses format
strings (explained below) as compact descriptions of the lay-out of the C
structs and the intended conversion to/from Python values. This can be
used in handling binary data stored in files or from network connections,
among other sources." (out of the python-doc).

learning by example: 

to convert a 4 byte integer you'd write: 
	"struct.unpack("=I",str_of_len_4)[0]"

= means native endian format - use the machine's endian format
I means unsigned int
str_of_len_4 has to be a binary string of length 4 containing the int
and the [0] at the end is neccessary cause unpack *always* returns a list,
even if only one value is converted (otherwise it'd be [2387], for example).
this is even stackable: 
	"struct.unpack("=IIH", str_of_len_10)[0]"
converts two unsigned ints, one unsigned short. great, huh? :-)

Hope this is what you need. your explanations seemed rather complicated to
me ;-)


greetings, 

		axel.





More information about the Python-list mailing list