2 回答

TA貢獻2051條經驗 獲得超10個贊
由于輸入以 8 位字節編碼,但輸出以 6 位(radix-64)字節編碼,因此輸出需要是輸入大小的 8/6 = 4/3 倍。所以這應該有效:
package main
import (
? ? "encoding/base64"
? ? "fmt"
)
func main() {
? ? str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"
? ? dst := make([]byte, len(str)*len(str)/base64.StdEncoding.DecodedLen(len(str)))
? ? _, err := base64.StdEncoding.Decode(dst, []byte(str))
? ? if err != nil {
? ? ? ? fmt.Println("error:", err)
? ? ? ? return
? ? }
? ? fmt.Printf("%s\n", dst)
}
基于其中的實現,DecodedLen()一般情況下返回輸入長度的3/4倍:
// DecodedLen returns the maximum length in bytes of the decoded data
// corresponding to n bytes of base64-encoded data.
func (enc *Encoding) DecodedLen(n int) int {
? ? if enc.padChar == NoPadding {
? ? ? ? // Unpadded data may end with partial block of 2-3 characters.
? ? ? ? return n * 6 / 8
? ? }
? ? // Padded base64 should always be a multiple of 4 characters in length.
? ? return n / 4 * 3
}
但最后,我最終只是將輸入轉換為字符串并使用,DecodeString()因為它已經體現了這個邏輯。
- 2 回答
- 0 關注
- 191 瀏覽
添加回答
舉報