亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Go的base64.StdEncoding.Decode()方法:如何選擇目標字節片的大小?

使用Go的base64.StdEncoding.Decode()方法:如何選擇目標字節片的大小?

Go
肥皂起泡泡 2023-08-14 14:42:27
我想使用Decode(https://golang.org/pkg/encoding/base64/#Encoding.Decode)來解碼一段字節,并且想知道,給定這個方法簽名,func (enc *Encoding) Decode(dst, src []byte) (n int, err error)如何選擇dst字節切片的大小,使其足夠大以捕獲輸出。例如,此代碼片段(改編自https://golang.org/pkg/encoding/base64/#Encoding.DecodeString)package mainimport (    "encoding/base64"    "fmt")func main() {    str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/"    dst := make([]byte, 1024)    _, err := base64.StdEncoding.Decode(dst, []byte(str))    if err != nil {        fmt.Println("error:", err)        return    }    fmt.Printf("%s\n", dst)}印刷some data with  and ?但是,如果我選擇的尺寸dst太?。ɡ?),我會感到index out of range恐慌:panic: runtime error: index out of rangegoroutine 1 [running]:encoding/base64.(*Encoding).decodeQuantum(0xc000084000, 0x1193018, 0x0, 0x0, 0xc000080f30, 0x20, 0x20, 0x4, 0x10, 0x10, ...)    /usr/local/Cellar/[email protected]/1.12.12/libexec/src/encoding/base64/base64.go:352 +0x567encoding/base64.(*Encoding).Decode(0xc000084000, 0x1193018, 0x0, 0x0, 0xc000080f30, 0x20, 0x20, 0xc000080f38, 0x105779d, 0x10b16e0)    /usr/local/Cellar/[email protected]/1.12.12/libexec/src/encoding/base64/base64.go:500 +0x5aamain.main()    /Users/kurt/Documents/Scratch/base64_decode.go:11 +0xb4exit status 2如何dst根據 的大小選擇 的大小src以可靠地解碼輸入?
查看完整描述

2 回答

?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

您應該使用它base64.DecodedLen來查找解碼輸入所需的最大大小,然后使用n返回的值Decode來找出它實際寫入該切片的時間。



查看完整回答
反對 回復 2023-08-14
?
侃侃無極

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()因為它已經體現了這個邏輯。


查看完整回答
反對 回復 2023-08-14
  • 2 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號