使用字节切片解压缩压缩的 ZLib 字符串

Decompressing a compressed ZLib string with Byte Slicing

我在我的代码中使用了以下几行:

payloadByte = zlib.compress(str.encode("hello"))
print(zlib.decompress(payloadByte[0:4]))

但是,zlib 抛出以下错误:

zlib.error: Error -5 while decompressing data: incomplete or truncated stream

我需要使用字节切片技术,因为我必须从大字节数组中的特定点解压缩。我使用结构创建了这个字节数组,如下所示:

messageIdByte = struct.pack("i", int(messageId))
payloadByte = zlib.compress(str.encode("hello"))
return messageIdByte + payloadByte

在这个例子中,我已经像这样解压了结构:

messageId = struct.unpack("i", bytes[0:4])[0]

现在,我需要从字节数组中解压缩字符串,但是获取特定字节 [4:8] 会产生此错误。

问题可能是您尝试解压缩的数据不是您认为的大小。例如,在您的示例中,当您使用 zlib 压缩字符串 "hello" 时,结果为 13 个字节长,但您的代码假定生成的压缩字符串为 5 个字节。尝试这样的事情:

x = len(payloadByte)
# elsewhere in the code where decompression happens
zlib.decompress(bytes[4:(4+x)])

确保您检索到整个压缩数据块。