将文件编码到Golang的base64中时丢失了一个字节
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")
}
输出:
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")
}
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 base64.newencoder docs :
因此:
另请参见Doc的示例:
From the base64.NewEncoder docs:
So:
see also the doc's example: