LouisChiffre
LouisChiffre

Reputation: 701

how to detect quickly if a string is zlib compressed?

What's the quickest way in python to determine if a string was compressed by zlib. I am using this currently.

def iscompressed(data):
    result = True
    try:
        s =zlib.decompress(data)
    except:
        result = False  
    return result

I am sure there is a more elegant way.

Upvotes: 11

Views: 10028

Answers (2)

Tobias Schittkowski
Tobias Schittkowski

Reputation: 2251

You can check the first 2 Byte for the header information - it is, however, not 100% safe.

See http://www.faqs.org/rfcs/rfc1950.html, chapter 2.2

Upvotes: 12

Amber
Amber

Reputation: 526573

While the only way to be 100% sure is to actually try to decompress it, you can make a reasonable guess by looking for the zlib compression method + flags header bits:

http://www.faqs.org/rfcs/rfc1950.html

Upvotes: 4

Related Questions