Home > database >  zlib difference between golang and python
zlib difference between golang and python

Time:10-18

Go: package main

import (
    "bytes"
    "encoding/hex"
    "compress/zlib"
)
func zlibCompress(src []byte) []byte {
    var in bytes.Buffer
    w, _ := zlib.NewWriterLevel(&in, zlib.DefaultCompression)
    w.Write(src)
    w.Close()
    return in.Bytes()
}
func main(){
    fmt.Println(hex.EncodeToString(zlibCompress([]byte{'1'})))
}

Output:

789c3204040000ffff00320032

Python:

compressed_data = zlib.compress(b"1")
print(compressed_data.hex())

Output:

789c33040000320032

What is the defference bettween "3204040000ffff" and "330400" ? I googled "zlib 0000ffff" and found that "0000ffff" is the flag of flush.

because I can not modify the server-side, so I must make my go project fit the server-side. I tried pass the data compresed by golang to the server-side,but the server refuse it because it can't decompress the data.

How to get python-style result in golang?

CodePudding user response:

Yes, an empty stored block was added by Golang. No, this doesn't matter for you. Both will decompress to the same thing. Do not worry about getting the same result. Both outputs are valid.

The first one:

! infgen 3.0 output
!
zlib
!
fixed
literal '1
end
!
last
stored
end
!
adler

and the second:

! infgen 3.0 output
!
zlib
!
last
fixed
literal '1
end
!
adler

Golang is adding the stored block as a last block to end the deflate stream, whereas Python took into account that that was all of the data, so it made the first block the last block.

CodePudding user response:

I have found the 3rd-party package https://github.com/4kills/go-zlib ,which provides the same result with python.

  • Related