2

I am using the following lines in my code:

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

However, zlib throws the following error:

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

I need to use byte slicing techniques due to the fact that I have to decompress from a specific point in a large byte array. I have created this byte array using a struct, like so:

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

In this example, I have already unpacked the struct like so:

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

Now, I need to decompress the string from the byte array, but getting the specific bytes [4:8] yields this error.

Rob
  • 35
  • 6
  • Could you clarify why you need to do this? In the example you give the issue isn't that you're decompressing a slice of an array, it's that you're decompressing something that isn't a valid, zlib compressed chunk of data. – Irisshpunk Dec 29 '16 at 00:15
  • I have updated my question to hopefully reflect what I want the code to do. – Rob Dec 29 '16 at 00:19
  • Might this be what you are looking for: http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib ? – Dekel Dec 29 '16 at 00:19

1 Answers1

1

The issue is probably that the data you are trying to decompress is not of the size that you think it is. For instance, in your example, when you compress the string "hello" using zlib, the result is 13 bytes long but your code assumes that the resulting compressed string is 5 bytes. Try something like this:

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

to make sure that you're retrieving the entire chunk of compressed data.

Irisshpunk
  • 758
  • 5
  • 8
  • You're completely right. In my code, I _was_ passing the length, but it was the length of the string, and not the length of the zlib compressed string. Thanks – Rob Dec 29 '16 at 00:27