noob stuck on reading double

John Machin sjmachin at
Tue Jan 29 21:29:31 CET 2008

[I can't see Hannah's posting(s) with my news client (Thunderbird), nor 
with Google Groups]

Joe Riopel wrote:
> Since you're unpacking it with the 'd' format character I am assuming
> a "doubleword" field is a double.

Given Hannah has sensibly stated up front that she is a noob, I would 
assume nothing from her code.

Given "doubleword" is Intel/MS-speak for "32-bit quantity", and 
following the strong hint of repeat-every-4-bytes from the printed 
gibberish (e.g. "Q???Q???Q???Q???Q?") I'd *guess* that a "doubleword" is 
a signed or unsigned 32-bit integer. Now let's check the guess:

> You said you had 113 of them in the
> binary file.

There are about 170 bytes of gibberish, that I saw in Joe's second 
reply. Hannah, don't do:
     print gibberish
     print len(gibberish), repr(gibberish)

What is the size of the file? 4 * 113 -> 452, 8 * 113 = 904

> You should be doing something like this:
>                 file = open('data.bin', 'rb')
don't shadow the 'file' built-in function
where else would it be positioned???
>                 raw =
>                 unpacked = unpack('113d', raw)
>                 for i in range(0,113):
>                         print unpacked[i]
>                 file.close()

I suggest that Hannah try something like this:

from struct import unpack
f = open('data.bin', 'rb')
raw =
nbytes = len(raw)
print 'nbytes', nbytes
print '32-bit signed integer', unpack('<%di' % (nbytes // 4), raw)
print '32-bit unsigned integer', unpack('<%dI' % (nbytes // 4), raw)
print '64-bit floating point', unpack('<%dd' % (nbytes // 8), raw)

and choose depending on what output best meets her expectations.

Note: the "<" in the above is another guess based on "doubleword" -> 
Intel -> little-endian. If struct.unpack is unhappy or if all three 
results look like rubbish, change the "<" to a ">" and try again ... if 
in doubt, come back for more advice. If you do, please include the 
output from starting Python at the shell prompt and peeking at 
sys.byteorder -- this i swhat that produces on my machine:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys; sys.byteorder


More information about the Python-list mailing list