2016-12-29 227 views
2

我用我下面几行代码:解压压缩zlib的字符串字节切片

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]会产生此错误。

+0

你能否澄清你为什么需要这样做?在这个例子中,你提出的问题不是你正在解压缩数组的一部分,而是你正在解压缩一些不是有效的,zlib压缩的数据块。 – Irisshpunk

+0

我已更新我的问题,希望能够反映出我想要的代码。 – Rob

+0

可能这是你在找什么:http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib? – Dekel

回答

1

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

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

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

+0

你完全正确。在我的代码中,我_was_传递了长度,但它是字符串的长度,而不是zlib压缩字符串的长度。谢谢 – Rob