将文件编码到Golang的base64中时丢失了一个字节

发布于 2025-02-10 10:21:54 字数 935 浏览 2 评论 0原文

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "io"
    "log"
    "os"
)

func b(name string) {
    f, err := os.Open(name)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    buf := new(bytes.Buffer)
    binval := base64.NewEncoder(base64.StdEncoding, buf)
    if _, err := io.Copy(binval, f); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s\n", buf.String()[buf.Len()-5:])
}

func main() {
    b("soccer.jpg")
    b("soccer2.jpg")
}

supcer.jpg sopcer2.jpg

输出:

bodqhrohro@debian:/tmp$ go run base64.go 
nuNf/
nuNf/

第一个文件与第二个文件相同,仅次于最后一个字节。它们产生相同的base64字符串。怎么了?

我经历了GO1.15.9和GO1.18.3。

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "io"
    "log"
    "os"
)

func b(name string) {
    f, err := os.Open(name)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    buf := new(bytes.Buffer)
    binval := base64.NewEncoder(base64.StdEncoding, buf)
    if _, err := io.Copy(binval, f); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s\n", buf.String()[buf.Len()-5:])
}

func main() {
    b("soccer.jpg")
    b("soccer2.jpg")
}

soccer.jpg
soccer2.jpg

Output:

bodqhrohro@debian:/tmp$ go run base64.go 
nuNf/
nuNf/

The first file is identical to the second one just with the last byte cut out. They yield an identical base64 string. What's wrong?

I experience it with go1.15.9 and go1.18.3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不弃不离 2025-02-17 10:21:54

来自 base64.newencoder docs

呼叫者必须关闭返回的编码器以部分冲洗任何一个
书面块。

因此:

binval.Close() // <- add this

fmt.Printf("%s\n", buf.String()[buf.Len()-5:])

另请参见Doc的示例

// Must close the encoder when finished to flush any partial blocks.
// If you comment out the following line, the last partial block "r"
// won't be encoded.
encoder.Close()

From the base64.NewEncoder docs:

the caller must Close the returned encoder to flush any partially
written blocks.

So:

binval.Close() // <- add this

fmt.Printf("%s\n", buf.String()[buf.Len()-5:])

see also the doc's example:

// Must close the encoder when finished to flush any partial blocks.
// If you comment out the following line, the last partial block "r"
// won't be encoded.
encoder.Close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文