So I am trying to write a program that encodes(and decodes) a string with this formula:
Decode: b64 decode -> zlib decode -> decoded string
Here is how i coded it:
def decode_level(level_data: str) -> str:
base64_decoded = base64.urlsafe_b64decode(level_data.encode())
decompressed = zlib.decompress(base64_decoded, 15 | 32)
return decompressed.decode()
But how do I reverse it? I mean how do I encode that string? I have tried this:
def encodeLevelData(lvlData: str) -> str:
eData = lvlData.encode() # eData -> encoded data
compressed = zlib.compress(eData, 15 | 32)
b64decoded = base64.urlsafe_b64encode(compressed)
return b64decoded
But it gives me an error on this line:
-> Exception has occurred: Bad compression: levelcompressed = zlib.compress(eData, 15 | 32)
Why does this error happen? And how do I fix it? Here is the string that im trying to encode: https://pastebin.com/4Dkz07yY
CodePudding user response:
It says the level is bad because the level is bad. You should have just gone to the documentation to see that the level for zlib.compress()
can only be in -1..9
.
It looks like you trying to give a wbits
value to the level
parameter. There is no wbits
parameter for zlib.compress()
. If you want to specify wbits
then you need to use z = zlib.compressobj()
and z.compress()
. (Again, actually reading the documentation is a huge help here.)
wbits = 15 | 32
for decompression means to look for either a zlib header, or a gzip header. That can't be given for compression, since you need to say what you want. (Ooh, look! That's in the documentation as well.) If you want a zlib header, use wbits = 15
. If you want a gzip header, use wbits = 15 | 16
.