Reading file bit by bit

Richard Thomas chardster at gmail.com
Mon Jun 7 05:31:08 EDT 2010


On Jun 7, 10:17 am, Peter Otten <__pete... at web.de> wrote:
> Alfred Bovin wrote:
> > I'm working on something where I need to read a (binary) file bit by bit
> > and do something depending on whether the bit is 0 or 1.
>
> > Any help on doing the actual file reading is appreciated.
>
> The logical unit in which files are written is the byte. You can split the
> bytes into 8 bits...
>
> >>> def bits(f):
>
> ...     while True:
> ...             b = f.read(1)
> ...             if not b: break
> ...             b = ord(b)
> ...             for i in range(8):
> ...                     yield b & 1
> ...                     b >>= 1
> ...>>> with open("tmp.dat", "wb") as f: # create a file with some example data
>
> ...     f.write(chr(0b11001010)+chr(0b10101111))>>> with open("tmp.dat", "rb") as f:
>
> ...     for bit in bits(f):
> ...             print bit
> ...
> 0
> 1
> 0
> 1
> 0
> 0
> 1
> 1
> 1
> 1
> 1
> 1
> 0
> 1
> 0
> 1
>
> but that's a very inefficient approach. If you explain what you are planning
> to do we can most certainly come up with a better alternative.
>
> Peter

You're reading those bits backwards. You want to read the most
significant bit of each byte first...

Richard.



More information about the Python-list mailing list