使用Python如何读取字节中的位?
我有一个文件,里面的第一个字节包含了一些编码的信息。在Matlab中,我可以用 var = fread(file, 8, 'ubit1')
这个命令一位一位地读取这个字节,然后通过 var(1), var(2)
等来获取每一位。
在Python中有没有类似的读取位的方式呢?
10 个回答
15
使用 numpy
非常简单,就像这样:
Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)
更多信息请查看这里:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html
34
你能操作的最小单位是字节。要在比特(bit)级别上进行操作,你需要使用位运算符。
x = 3
#Check if the 1st bit is set:
x&1 != 0
#Returns True
#Check if the 2nd bit is set:
x&2 != 0
#Returns True
#Check if the 3rd bit is set:
x&4 != 0
#Returns False
36
从一个文件中读取数据,先读取低位的部分。
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