Golang and Python zlib Discrepancy
When comparing the results of compressing a string using Python's zlib library and Go's flate package, differences arise. In this question, the Python version generates an output with an additional zero byte, while the Golang version does not.
The discrepancy stems from the different approaches taken by the two libraries. Python's zlib compresses data to a zlib format, which includes a header and checksum. In contrast, Go's flate directly implements the DEFLATE algorithm, producing a raw DEFLATE stream without the header or checksum.
To obtain an identical output from Go, modify the code to explicitly flush the buffer after writing the compressed data:
<code class="go">func compress(source string) []byte { buf := new(bytes.Buffer) w, _ := flate.NewWriter(buf, 7) w.Write([]byte(source)) w.Flush() return buf.Bytes() }</code>
However, it's important to note that the output of different compression libraries may not be byte-for-byte identical. While they aim for compatibility, the specific implementation details can lead to variations.
The above is the detailed content of Why does Go\'s flate package produce a different compressed output compared to Python\'s zlib library?. For more information, please follow other related articles on the PHP Chinese website!