How to Encode and Decode Hex in Go

Encode bytes to hex strings and decode hex strings back to bytes using Go's encoding/hex package.

Use the encoding/hex package to encode bytes to a hex string and decode a hex string back to bytes.

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	// Encode: bytes to hex string
	data := []byte("Hello")
	hexStr := hex.EncodeToString(data)
	fmt.Println(hexStr) // Output: 48656c6c6f

	// Decode: hex string to bytes
	decoded, err := hex.DecodeString(hexStr)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(decoded)) // Output: Hello
}