使用Python如何读取字节中的位?

2024-05-16 01:39:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,其中第一个字节包含编码信息。在Matlab中,我可以用var = fread(file, 8, 'ubit1')逐位读取字节,然后用var(1), var(2)等检索每一位

python中是否有等效的位读取器?


Tags: 文件信息编码字节var读取器filematlab
3条回答

你不可能一个一个地读取每一位,你必须一个字节一个字节地读取它。不过,您可以轻松地提取这些位:

f = open("myfile", 'rb')
# read one byte
byte = f.read(1)
# convert the byte to an integer representation
byte = ord(byte)
# now convert to string of 1s and 0s
byte = bin(byte)[2:].rjust(8, '0')
# now byte contains a string with 0s and 1s
for bit in byte:
    print bit

你能处理的最小单位是一个字节。要在位级别工作,需要使用bitwise operators

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

从文件中读取位,低位优先。

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

相关问题 更多 >