Data reading problem

Fredrik Lundh fredrik at pythonware.com
Sun Dec 19 11:00:14 EST 2004


Michal Szpadzik wrote:

> I have some problems with bits data reading. I have binary data file where data is written as 
> 12bits pack. I need to read it becouse there are saved values which have to processed later by my 
> program. I was wandering about reading 3bytes=24bits and split it by bits moving. If anyone know 
> how to do that please tell me or give me some code.
>
> My data example:
> 101001000101111010100101 etc
>
> i need to split it:
> x=101001000101   y=111010100101

assuming MSB first,

    a = ord(fp.read(1))
    b = ord(fp.read(1))
    c = ord(fp.read(1))

    x = (a << 4) + (b >> 4)
    y = ((b & 15) << 8) + c

should do the trick

if you need to read lots of 12-bit values, you can create a simple bitstream
generator:

    def bitstream(file, size=12):
        bitbuffer = bits = 0
        while 1:
            char = file.read(1)
            if not char:
                raise StopIteration
            bitbuffer = (bitbuffer << 8) | ord(char)
            bits = bits + 8
            while bits >= size:
                yield (bitbuffer >> (bits - size)) & ((1 << size) - 1)
                bits = bits - size

for example:

    file = open("file.dat", "rb")

    for word in bitstream(file):
        print hex(word)

prints

    0xa45
    0xea5

</F> 






More information about the Python-list mailing list