How to read bits from a file?

前端 未结 3 1043
长情又很酷
长情又很酷 2020-12-01 12:59

I know how to read bytes — x.read(number_of_bytes), but how can I read bits in Python?

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

3条回答
  •  时光取名叫无心
    2020-12-01 13:24

    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 = x.read(1)
    firstfivebits = b >> 3
    

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

    b = x.read(1)
    lastfivebits = b & 0b11111
    

    Some other useful bit manipulation info can be found here: http://wiki.python.org/moin/BitManipulation

提交回复
热议问题