Using Python How can I read the bits in a byte?

David picture David · Apr 5, 2010 · Viewed 68.5k times · Source

I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var = fread(file, 8, 'ubit1'), and then retrieve each bit by var(1), var(2), etc.

Is there any equivalent bit reader in python?

Answer

user97370 picture user97370 · Apr 5, 2010

Read the bits from a file, low bits first.

def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

for b in bits(open('binary-file.bin', 'r')):
    print b