golang/python zlib差异

2024-09-30 05:17:08 发布

您现在位置:Python中文网/ 问答频道 /正文

调试Python的zlib和golang的zlib之间的差异。为什么下面的结果不一样?在

compress.go

package main

import (
    "compress/flate"
    "bytes"
    "fmt"
)


func compress(source string) []byte {
    w, _ := flate.NewWriter(nil, 7)
    buf := new(bytes.Buffer)

    w.Reset(buf)
    w.Write([]byte(source))
    w.Close()

    return buf.Bytes()
}


func main() {
    example := "foo"
    compressed := compress(example)
    fmt.Println(compressed)
}

compress.py

^{pr2}$

结果

$ go version
go version go1.7.3 darwin/amd64
$ go build compress.go
$ ./compress
[74 203 207 7 4 0 0 255 255]
$ python --version
$ python 2.7.12
$ python compress.py
[74, 203, 207, 7, 0, 0, 0, 255, 255]

Python版本的第五个字节有0,而golang版本有4——是什么导致了不同的输出?在


Tags: gosourcebytesmainversionexamplebytecompress
1条回答
网友
1楼 · 发布于 2024-09-30 05:17:08

python示例的输出不是一个“完整的”流,它只是在压缩第一个字符串之后刷新缓冲区。通过将Close()替换为Flush(),可以从Go代码中获得相同的输出:

https://play.golang.org/p/BMcjTln-ej

func compress(source string) []byte {
    buf := new(bytes.Buffer)
    w, _ := flate.NewWriter(buf, 7)
    w.Write([]byte(source))
    w.Flush()

    return buf.Bytes()
}

但是,您将比较python中zlib的输出,后者在内部使用DEFLATE来生成zlib格式的输出,而Go中的flate是一个DEFLATE实现。我不知道您是否可以让pythonzlib库输出原始的、完整的DEFLATE流,但是尝试让不同的库输出压缩数据的逐字节匹配似乎没有用或不可维护。压缩库的输出只能保证是兼容的,而不是完全相同的。在

相关问题 更多 >

    热门问题