how can i decode the string of base64?

2,574 views
Skip to first unread message

singochina

unread,
May 25, 2011, 12:36:23 PM5/25/11
to golang-nuts
Hi,

I know how to encode the string to base64 in golang, but got question
how to decode the string of base64? i search on website, but cannot
got any sample code for decode. is iz anyone can tell me how to decode
for base64?

SGV5LCBCaW5nbyEh


Thanks & Regards,
Singo

roger peppe

unread,
May 25, 2011, 12:41:21 PM5/25/11
to singochina, golang-nuts
see encoding/base64

for example:
package main


import (
"os"
"io"
"encoding/base64"
"strings"
)

func main() {
r := base64.NewDecoder(base64.StdEncoding,
strings.NewReader("SGV5LCBCaW5nbyEh"))
io.Copy(os.Stdout, r)

singochina

unread,
May 25, 2011, 2:22:19 PM5/25/11
to golang-nuts
Thx a lot !


and i found another way to do that in the mail list :)

Archos,
While the base64 package may be awkward and not very idiomatic for
your purpose, that doesn't mean it's wrong. You could simply provide
a
nicer view of the package yourself.
For example,
package main
import (
"fmt"
"encoding/base64"
)
func Encode(encBuf, bin []byte, e64 *base64.Encoding) []byte {
maxEncLen := e64.EncodedLen(len(bin))
if encBuf == nil || len(encBuf) < maxEncLen {
encBuf = make([]byte, maxEncLen)
}
e64.Encode(encBuf, bin)
return encBuf[0:]
}

func Decode(decBuf, enc []byte, e64 *base64.Encoding) []byte {
maxDecLen := e64.DecodedLen(len(enc))
if decBuf == nil || len(decBuf) < maxDecLen {
decBuf = make([]byte, maxDecLen)
}
n, err := e64.Decode(decBuf, enc)
_ = err
return decBuf[0:n]
}

func main() {
// binary data
bin := []byte("testing base64..")
// base64 standard encoding
e64 := base64.StdEncoding
// encode
enc := Encode(nil, bin, e64)
// decode
dec := Decode(nil, enc, e64)
// results
fmt.Println("Equal:", string(bin) == string(dec))
fmt.Println("bin:", len(bin), bin)
fmt.Println("enc:", len(enc), string(enc))
fmt.Println("dec:", len(dec), dec)
}

Which, using the idiomatic Go slice, gives the following neat and
tidy
and intuitive results.
bin: 16 [116 101 115 116 105 110 103 32 98 97 115 101 54 52 46 46]
enc: 24 dGVzdGluZyBiYXNlNjQuLg==
dec: 16 [116 101 115 116 105 110 103 32 98 97 115 101 54 52 46 46]
Peter
On Apr 30, 7:10 am, Archos <raul....@sent.com> wrote:

zbin...@gmail.com

unread,
Sep 24, 2015, 11:43:22 PM9/24/15
to golang-nuts
you can try this free online service to decode base64 to string online(http://www.online-code.net/base64-string.html).

ramed...@gmail.com

unread,
Nov 13, 2015, 8:33:52 AM11/13/15
to golang-nuts
Thank you!

p.s base64.StdEncoding removed last symbol from result {"asd":"1","gg":"12"
base64.RawStdEncoding works fine {"asd":"1","gg":"12"}
Reply all
Reply to author
Forward
0 new messages