Encode/Decode base64

前端 未结 5 1017
陌清茗
陌清茗 2021-02-06 22:06

here is my code and i don\'t understand why the decode function doesn\'t work.

Little insight would be great please.

func EncodeB64(message string) (reto         


        
5条回答
  •  深忆病人
    2021-02-06 22:55

    @Denys Séguret's answer is almost 100% correct. As an improvement to avoid wasting memory with non used space in base64Text, you should use base64.DecodedLen. Take a look at how base64.DecodeString uses it. It should look like this:

    func main() {
        message := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
    
        base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
    
        n, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
        fmt.Println("base64Text:", string(base64Text[:n]))
    }
    

    Try it here.

提交回复
热议问题