zlib在Golang和Python之间的区别是什么?

huangapple go评论118阅读模式
英文:

zlib difference between golang and python

问题

Go语言和Python语言在使用zlib压缩算法时的结果存在差异。具体来说,Go语言使用zlib.NewWriterLevel函数创建压缩器时,默认的压缩级别为zlib.DefaultCompression,而Python语言使用zlib.compress函数时,默认的压缩级别为-1(即使用默认压缩级别)。这导致了两者在压缩同一数据时得到的结果不同。

要在Go语言中获得与Python相同的结果,可以使用zlib.NewWriter函数创建压缩器,并将压缩级别设置为-1。修改后的Go代码如下:

package main

import (
	"bytes"
	"encoding/hex"
	"compress/zlib"
	"fmt"
)

func zlibCompress(src []byte) []byte {
	var in bytes.Buffer
	w := zlib.NewWriter(&in)
	w.Write(src)
	w.Close()
	return in.Bytes()
}

func main() {
	fmt.Println(hex.EncodeToString(zlibCompress([]byte{'1'})))
}

这样修改后,Go语言的输出结果将与Python的输出结果一致。

英文:

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?

答案1

得分: 1

是的,Golang添加了一个空的存储块。不过,这对你来说并不重要。两者都会解压缩成相同的内容,所以不用担心结果不同。两个输出都是有效的。

第一个输出:

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

第二个输出:

! infgen 3.0 输出
!
zlib
!
last
fixed
literal '1
end
!
adler

Golang将存储块作为最后一个块添加到结束的压缩流中,而Python考虑到这是所有的数据,所以将第一个块作为最后一个块。

英文:

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.

huangapple
  • 本文由 发表于 2022年10月17日 22:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/74098712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定