How to read bits from a file?

前端 未结 3 1062
长情又很酷
长情又很酷 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:25

    This appears at the top of a Google search for reading bits using python.

    I found bitstring to be a good package for reading bits and also an improvement over the native capability (which isn't bad for Python 3.6) e.g.

    # import module
    from bitstring import ConstBitStream
    
    # read file
    b = ConstBitStream(filename='file.bin')
    
    # read 5 bits
    output = b.read(5)
    
    # convert to unsigned int
    integer_value = output.uint
    

    More documentation and details here: https://pythonhosted.org/bitstring/index.html

提交回复
热议问题