python and bit shifts and byte order, oh my!

Francesco Bochicchio bockman at
Sat Sep 11 11:08:38 CEST 2004

On Thu, 09 Sep 2004 22:21:42 -0500, Reid Nichol wrote:

> I played with bit shifts on my PC and tried the same thing on a Mac OS X 
> machine.  They produced the same results, so I would assume that the way 
> the bits and how they are interpreted are as in this link:
> At least in memory while the interpreter is running.
> It's my first attempt down there and I need to know.  So, is this how 
> Python works at the bit level?

I had  similar problems, not for reading/write binary files but to
pack/unpack network binary messages, with bitfields in it, between
big-endian and little-endian computers.

I ended up writing a 'bitstring' class that is loaded with a bunch of
bytes ( e.g. the output of a socket.recv () or a ) and is 
able to read/set any arbitrary group of bits in it in a portable way,
which is not hard, since bits operators works on 'logical intergers' and
are independent of byte order, as others pointed out (I believe this is
also true i C and other languages).

I'm not showing my code, because since then I discovered that in the Net
there are better implementation than mine :-). Just google for "python bit
manipulation" and you will find examples like this:

which should work with arbitrary length bitstrings, since bit operators
work on long integers, also :-)

More information about the Python-list mailing list