struct module - '<q' equivalent for old python?

Tim Peters tim.one at comcast.net
Sun Apr 28 13:34:09 EDT 2002


[jaf]
> In my application, I need to be able to read and write a 64-bit integer
> (in little-endian format) from/to a file.  For Python 2.2, the struct
> module has a nice '<q' datatype argument that will do just that, but it
> isn't implemented in older versions and throws an exception.
>
> Does anyone know of a good alternative method I could use as a fallback
> in this case?  Some of the platforms I need to support don't have
> Python2.2 readily available, so I'd like to be able support older
> versions of Python, if possible.

What does "good" mean?  If you can settle for correct, these will work fine:

def write_leq(f, i):
    for count in range(8):
        f.write(chr(i & 0xff))
        i = i >> 8

def read_leq(f):
    result = 0L
    for shift in range(0, 64, 8):
        result = result | (long(ord(f.read(1))) << shift)
    if result >> 63:
        result = result - (1L << 64)
    return result

Be sure f is opened in binary mode.  Those do "the obvious" things, viewing
a 64-bit signed int as 8 unsigned 8-bit fields.  If you need it to be
zippier, you can use the struct module to view a 64-bit signed int as 2
mixed-sign 32-bit fields, although it's harder to understand:

import struct

def write_leq(f, i):
    f.write(struct.pack('<Ii', i & 0xffffffffL, i >> 32))

def read_leq(f):
    lo, hi = struct.unpack('<Ii', f.read(8))
    return (long(hi) << 32) | lo






More information about the Python-list mailing list