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

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

編碼/解碼 base64

編碼/解碼 base64

Go
蠱毒傳說 2021-06-03 13:39:54
這是我的代碼,我不明白為什么解碼功能不起作用。一點點洞察力會很好。func EncodeB64(message string) (retour string) {    base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))    base64.StdEncoding.Encode(base64Text, []byte(message))    return string(base64Text)}func DecodeB64(message string) (retour string) {    base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))    base64.StdEncoding.Decode(base64Text, []byte(message))    fmt.Printf("base64: %s\n", base64Text)    return string(base64Text)}它給了我:[解碼錯誤 - 輸出不是 utf-8][解碼錯誤 - 輸出不是 utf-8]
查看完整描述

3 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

DecodedLen返回最大長度。


此長度對于調整緩沖區大小很有用,但不會寫入緩沖區的一部分,因此不會是有效的 UTF-8。


您必須僅使用Decode函數返回的實際寫入長度。


l, _ := base64.StdEncoding.Decode(base64Text, []byte(message))

log.Printf("base64: %s\n", base64Text[:l])


查看完整回答
反對 回復 2021-06-07
?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

len 前綴是膚淺的,會導致無效的 utf-8 錯誤:


package main


import (

        "encoding/base64"

        "fmt"

        "log"

)


func main() {

        str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))

        fmt.Println(str)


        data, err := base64.StdEncoding.DecodeString(str)

        if err != nil {

                log.Fatal("error:", err)

        }


        fmt.Printf("%q\n", data)

}

輸出


SGVsbG8sIHBsYXlncm91bmQ=

"Hello, playground"

編輯:我讀得太快了,len 沒有用作前綴。dystroy 做對了。


查看完整回答
反對 回復 2021-06-07
  • 3 回答
  • 0 關注
  • 269 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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