python and bit shifts and byte order, oh my!

Jason Lai jmlai at
Fri Sep 10 22:17:14 CEST 2004

Reid Nichol wrote:
> Phil Frost wrote:
>> The standard 'struct' module provides methods to specify the byte order
>> of the input.
>> On Fri, Sep 10, 2004 at 02:13:52PM -0500, Reid Nichol wrote:
>>>> The code that writes x to a file and reads it from a file is
>>>> what you have to worry about.
>>> So, I have to handle the byte order myself during file i/o.
>>> Thank you Grant and Daniel!  I cleared up a a bunch of my fuzziness :)
> It's my understanding that pack and unpack of the struct module returns 
> strings and not rearranged integers.
> At any rate I would rather do it myself if only to teach myself 
> something about this.

pack returns a string. Which is a sequence of characters, which also 
happen to be bytes. So you write the string (sequence of bytes) to the 
file. I don't think you usually need to rearrange integers in memory; 
it's mainly when you're writing to disk.

unpack returns a tuple of objects according to the format string. So 
struct.unpack("!i", "abcd") returns (1633837924,). In your case, you'd 
read in 4 bytes and unpack it to a 32-bit int.

If efficiency isn't important, you could forget about the whole 
byte-order thing and just read/write it byte-by-byte. Then you can think 
of the file as a bit-stream (everything gets written in order and read 
back in order), although you still have to read/write a whole 8-bit byte 
at a time.

  - Jason Lai

More information about the Python-list mailing list