[Tutor] Getting a binary value from a file
Kent Johnson
kent37 at tds.net
Wed Nov 28 19:58:37 CET 2007
Chuk Goodin wrote:
> I have a file full of "integers". If I get a file handle (e.g. file1)
> and then read something in, I get back some hex value. How can I go on
> to use that in my program?
>
> For example, in interactive mode, file1.read(4) gets me an output of
> '/x00/x00/x00/x1c' (might not be exact, I'm at a different computer
> right now). Can I just store that in a variable and then somehow convert
> it to decimal?
Use the struct module:
In [26]: import struct
In [29]: struct.unpack('>i', '\x00\x00\x00\x1c')[0]
Out[29]: 28
Note the value returned from unpack is a tuple, hence the [0] subscript.
http://docs.python.org/lib/module-struct.html
> Sorry if this is too newbish.
Not for this list!
Kent
More information about the Tutor
mailing list