Python:尝试将流分割成一口大小的块

问题描述 投票:0回答:1

目前我正在读一个内流并将其拼接成3个字节的块:

instream_chunks = [instream[i:i+3]for i in range (0, len(instream), 3)]

我没做的就是把这个插件拆分成22位大小的块。有没有办法在Python中做到这一点?

编辑:创建了一个instream(用于测试目的),如下所示:

instream = open('C:/xxx/test.txt', 'rb+')

然后,此函数将在此函数中使用

def write(self, instream: typ.BinaryIO):

从我上面描述的内容开始。

python binary byte bit
1个回答
0
投票

假设您有足够的内存,您可以将instream转换为位列表,然后根据需要对其进行切片。

def access_bit(data, num):
    base = int(num/8)
    shift = num % 8
    return (data[base] & (1<<shift)) >> shift

def to_bits(instream):
    ba = bytearray(instream.read())
    return [access_bit(ba,i) for i in range(len(ba)*8)]

>>>to_bits(open('test.txt','rb'))

[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0]

否则,您将需要读取所需大小的多个较小的块,然后在每个块上使用上述方法。例如,您读取22 * 4 = 88位或11个字节,然后调用to_bits,将生成的数组拆分为4个22位块,然后重复。

© www.soinside.com 2019 - 2024. All rights reserved.