Complete Guide to the encoding/hex and encoding/base64 Packages

Use encoding/hex for hexadecimal conversion and encoding/base64 for Base64 encoding/decoding in Go.

Use encoding/hex to convert bytes to/from hexadecimal strings and encoding/base64 for Base64 encoding/decoding. Both packages provide standard functions for encoding and decoding data in Go.

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

func main() {
    data := []byte("Hello, World!")

    // Hex encoding and decoding
    hexEncoded := hex.EncodeToString(data)
    hexDecoded, _ := hex.DecodeString(hexEncoded)
    fmt.Println("Hex:", hexEncoded, string(hexDecoded))

    // Base64 encoding and decoding
    b64Encoded := base64.StdEncoding.EncodeToString(data)
    b64Decoded, _ := base64.StdEncoding.DecodeString(b64Encoded)
    fmt.Println("Base64:", b64Encoded, string(b64Decoded))
}