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

Dav*_*vid 33 python byte bits

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

python中有没有相同的位读取器?

小智 26

首先读取文件中的位,低位.

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
Run Code Online (Sandbox Code Playgroud)

  • 它首先给出低位(这是很自然的,因为它也首先给出低字节)。但是如果你想要其他顺序,你可以将 `xrange(8)` 更改为 `reversed(xrange(8))`。 (2认同)

Bri*_*ndy 20

你能够使用的最小单位是一个字节.要在位级别工作,您需要使用按位运算符.

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
Run Code Online (Sandbox Code Playgroud)

  • 您是否介意添加更多信息,因为OP显然看起来像初学者? (3认同)

Dan*_*l G 10

您将无法逐个读取每个位 - 您必须逐字节读取它.但是,您可以轻松地提取出来:

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
Run Code Online (Sandbox Code Playgroud)


Mik*_*l V 9

有了numpy它很容易这样的:

Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)
Run Code Online (Sandbox Code Playgroud)

更多信息:http:
//docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html


jfs*_*jfs 6

为了从文件中读取一个字节:bytestring = open(filename, 'rb').read(1)。注意:文件以二进制模式打开。

要获取位,请将字节串转换为整数:byte = bytestring[0](Python 3)或byte = ord(bytestring[0])(Python 2)并提取所需的位(byte >> i) & 1::

>>> for i in range(8): (b'a'[0] >> i) & 1
... 
1
0
0
0
0
1
1
0
>>> bin(b'a'[0])
'0b1100001'
Run Code Online (Sandbox Code Playgroud)


Fra*_*sco 5

加入以前使用的一些答案:

[int(i) for i in "{0:08b}".format(byte)]
Run Code Online (Sandbox Code Playgroud)

对于从文件读取的每个字节。0x88字节示例的结果为:

>>> [int(i) for i in "{0:08b}".format(0x88)]
[1, 0, 0, 0, 1, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)

您可以将其分配给变量并按照您的初始请求进行工作。“ {0.08}”是为了保证完整的字节长度