我正在尝试将字节数组编码为 Base64 并遇到两个问题。我可以用 来做到这一点base64.StdEncoding.EncodedLen(text),但我担心这很昂贵,所以我想看看我是否可以用 来做到这一点len(text)。这是代码(这些函数被命名为“Marshal”,因为我在 JSON 封送处理期间将它们用作字段转换器):
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
)
func main() {
b := make([]byte, 60)
_, _ = rand.Read(b)
// Marshal Create Dst Buffer
MarshalTextBuffer(b)
// Marshal Convert to String
MarshalTextStringWithBufferLen(b)
// Marshal Convert to String
MarshalTextStringWithDecodedLen(b)
}
func MarshalTextBuffer(text []byte) error {
ba := base64.StdEncoding.EncodeToString(text)
fmt.Println(ba)
return nil
}
func MarshalTextStringWithBufferLen(text []byte) error {
ba := make([]byte, len(text)+30) // Why does len(text) not suffice? Temporarily using '30' for now, just so it doesn't overrun.
base64.StdEncoding.Encode(ba, text)
fmt.Println(ba)
return nil
}
func MarshalTextStringWithDecodedLen(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]
为什么中间的MarshalTextStringWithBufferLen需要额外的填充?
是base64.StdEncoding.EncodedLen一个代价高昂的函数(比如我可以用底层函数解决它,但我担心成本)。
互换的青春
相关分类