我正在嘗試將字節數組編碼為 Base64 并遇到兩個問題。我可以用 來做到這一點base64.StdEncoding.EncodedLen(text),但我擔心這很昂貴,所以我想看看我是否可以用 來做到這一點len(text)。這是代碼(這些函數被命名為“Marshal”,因為我在 JSON 封送處理期間將它們用作字段轉換器):package mainimport ( "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一個代價高昂的函數(比如我可以用底層函數解決它,但我擔心成本)。
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
Base-64 編碼將二進制數據(每字節 8 位)存儲為文本(每字節使用 6 位),因此每 3 個字節被編碼為 4 個字節(3x8 = 4x6)。所以len(text) + 30
在你的代碼中是錯誤的,并且應該是len(text)*4/3
(如果 len(text) 可以被 3 整除)但是為了提高可讀性并避免你應該用來base64.StdEncoding.EncodedLen()
獲取長度的錯誤。
如果您查看代碼,base64.StdEncoding.EncodedLen
您會發現它與您自己進行計算一樣快(特別是因為它是內聯的)。
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消