Hugo Medina Hugo Medina - 1 year ago 115
Python Question

How to read bits from a file?

I know how to read bytes —
, but how can I read bits in Python?

I have to read only 5 bits (not 8 bits [1 byte]) from a binary file

Any ideas or approach?

Answer Source

Python can only read a byte at a time. You'd need to read in a full byte, then just extract the value you want from that byte, e.g.

b =
firstfivebits = b >> 3

Or if you wanted the 5 least significant bits, rather than the 5 most significant bits:

b =
lastfivebits = b & 0b11111

Some other useful bit manipulation info can be found here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download