Golang encoding/hex.Decode() function example

package encoding/hex

Decode decodes src(2nd parameter) into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst (1st parameter). If Decode encounters invalid input, it returns an error describing the failure.

Golang encoding/hex.Decode() function usage example :

 package main

 import (
 "encoding/hex"
 "fmt"
 "os"
 )

 func main() {
 str := "abcd"
 src := []byte(str)

 dst := make([]byte, hex.DecodedLen(len(src)))

 num, err := hex.Decode(dst, src)  // <----- here

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

 fmt.Printf("Number of bytes written : %v", num)
 }

Output :

Number of bytes written : 2

If Decode encounter error, it will explain why. For example :

encoding/hex: odd length hex string

exit status 1

Reference :

http://golang.org/pkg/encoding/hex/#Decode

Advertisement