python and bit shifts and byte order, oh my!

Grant Edwards grante at visi.com
Fri Sep 10 19:40:02 CEST 2004


On 2004-09-10, Reid Nichol <rnichol_rrc at yahoo.com> wrote:

>> CPUs differ in the way integers are stored in memory. But the shift 
>> operators of the CPU are implemented to work on logical integers in 
>> registers, not on consecutive bytes in memory.
>
> I'm wondering because the file format I'm trying to write uses 
> bit-packing, so I need to be able to write, for example, a 5 bit integer 
> to the disk.

I presume by "to disk" you mean to a file in a filesystem.

You can't do that under any OS and filesystem with which I'm
familiar. You can only write an integral number of bytes to a
file.  You can only write an integral number of blocks to disk
(a block is 512 bytes, typically)

> I do think regardless of language I'm going to have an unfun
> time doing this.  But, since cross platform is a want
> approching a need, I'd like to use Python.
>
> Would getting a specific bit from the integer be the same or
> would I have to worry about the byte-order?

You only have to worry about byte order when reading/writing
binary objects from/to a file.

> ie Would:
> x & SOMEBIT
> be portable?

Yes, that's portable.

The code that writes x to a file and reads it from a file is
what you have to worry about.

-- 
Grant Edwards                   grante             Yow!  Put FIVE DOZEN red
                                  at               GIRDLES in each CIRCULAR
                               visi.com            OPENING!!



More information about the Python-list mailing list