Skip to content

Instantly share code, notes, and snippets.

@kjk
Created November 5, 2019 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjk/f055282edd12292e0f5aaa3fa1537e80 to your computer and use it in GitHub Desktop.
Save kjk/f055282edd12292e0f5aaa3fa1537e80 to your computer and use it in GitHub Desktop.
Hex encode and decode
// collection: Essential Go
package main
import (
"bytes"
"encoding/hex"
"fmt"
"log"
)
func main() {
// :show start
d := []byte{0x01, 0xff, 0x3a, 0xcd}
s := hex.EncodeToString(d)
fmt.Printf("Hex: %s\n", s)
d2, err := hex.DecodeString(s)
if err != nil {
log.Fatalf("hex.DecodeString() failed with '%s'\n", err)
}
if !bytes.Equal(d, d2) {
log.Fatalf("decoded version is different than original")
}
// :show end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment