如何从文件中读取位? [英] How to read bits from a file?
问题描述
我知道如何读取字节 - x.read(number_of_bytes)
,但我怎样才能读取Python中的位?
I know how to read bytes — x.read(number_of_bytes)
, but how can I read bits in Python?
我必须从二进制文件中只读取5位(不是8位[1字节])
I have to read only 5 bits (not 8 bits [1 byte]) from a binary file
任何想法或方法?
推荐答案
Python一次只能读取一个字节。你需要读一个完整的字节,然后从那个字节中提取你想要的值,例如
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
或者如果你想要5个最低有效位,而不是5个最高有效位:
Or if you wanted the 5 least significant bits, rather than the 5 most significant bits:
b = x.read(1)
lastfivebits = b & 0b11111
其他一些有用的位操作信息可以在这里找到:http://wiki.python.org/moin/BitManipulation
Some other useful bit manipulation info can be found here: http://wiki.python.org/moin/BitManipulation
这篇关于如何从文件中读取位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!