【发布时间】:2022-10-01 08:56:52
【问题描述】:
我正在尝试将字节数组编码为 Base64 并遇到两个问题。这是代码:
package main
import (
\"crypto/rand\"
\"encoding/base64\"
\"fmt\"
)
func main() {
b := make([]byte, 60)
_, _ = rand.Read(b)
// Unmarshal Create Dst Buffer
UnmarshalTextBuffer(b)
// Unmarshal Convert to String
UnmarshalTextStringWithBufferLen(b)
// Unmarshal Convert to String
UnmarshalTextStringWithDecodedLen(b)
}
func UnmarshalTextBuffer(text []byte) error {
ba := base64.StdEncoding.EncodeToString(text)
fmt.Println(ba)
return nil
}
func UnmarshalTextStringWithBufferLen(text []byte) error {
ba := make([]byte, len(text)+30) // Why does len(text) not suffice?
base64.StdEncoding.Encode(ba, text)
fmt.Println(ba)
return nil
}
func UnmarshalTextStringWithDecodedLen(text []byte) error {
ba := make([]byte, base64.StdEncoding.EncodedLen(len(text)))
base64.StdEncoding.Encode(ba, text)
fmt.Println(ba)
return nil
}
这是输出:
IL5CW8T9WSgwU5Hyi9JsLLkU/EcydY6pG2fgLQJsMaXgxhSh74RTagzr6b9yDeZ8CP4Azc8xqq5/+Cgk
[73 76 53 67 87 56 84 57 87 83 103 119 85 53 72 121 105 57 74 115 76 76 107 85 47 69 99 121 100 89 54 112 71 50 102 103 76 81 74 115 77 97 88 103 120 104 83 104 55 52 82 84 97 103 122 114 54 98 57 121 68 101 90 56 67 80 52 65 122 99 56 120 113 113 53 47 43 67 103 107 0 0 0 0 0 0 0 0 0 0]
[73 76 53 67 87 56 84 57 87 83 103 119 85 53 72 121 105 57 74 115 76 76 107 85 47 69 99 121 100 89 54 112 71 50 102 103 76 81 74 115 77 97 88 103 120 104 83 104 55 52 82 84 97 103 122 114 54 98 57 121 68 101 90 56 67 80 52 65 122 99 56 120 113 113 53 47 43 67 103 107]
为什么中间的UnmarshalTextStringWithBufferLen 需要额外的填充?
base64.StdEncoding.EncodedLen 是不是一个代价高昂的函数(例如我可以用底部函数解决它,但我担心代价)。
-
base64 编码的数据比原始数据大。使用函数 base64.StdEncoding.EncodedLen 从原始数据计算编码数据的大小。 EncodedLen documentation 链接方法的source code。与编码数据的总成本相比,该功能并不昂贵。
-
谢谢!如果您将此添加为答案,我很乐意接受。
-
我写评论是因为我认为我可以提供帮助,但我不明白你的具体问题。三个问题提出了不同的问题(标题,最后两段各一个)。标题更像是一个陈述,似乎与问题中 base64 包的实际使用无关(解组类似于解码,而不是编码)。编辑问题以使其更加集中。