Hex Encode And Decode Byte Slices

Encode bytes to lowercase hex with hex.EncodeToString, decode back losslessly, and see odd-length or invalid input fail with explicit errors.

GoData Integrity

Code

gosnippet
21 lines
package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	payload := []byte{0xde, 0xad, 0xbe, 0xef}

	encoded := hex.EncodeToString(payload)
	fmt.Println("encoded:", encoded)

	// 解码回字节:长度必须是 2 的倍数,字符必须是合法 hex 位
	decoded, err := hex.DecodeString(encoded)
	fmt.Println("decoded:", decoded, "err:", err)

	// 非法输入显式报错,不会静默产出垃圾数据
	bad, err := hex.DecodeString("xyz")
	fmt.Println("bad input:", bad, "err:", err)
}

What the code does

Count the function main as the entire surface area of Hex Encode And Decode Byte Slices.

Applying it

Running the file prints labeled results such as encoded:, decoded:, bad input: — each operation’s effect is visible in the output.

Statements that matter most here

payload := []byte{0xde, 0xad, 0xbe, 0xef}

Interactive Tools for This Topic

FAQ

What does Hex Encode And Decode Byte Slices print when run?
The script runs standalone; its 3 labeled outputs include `encoded:`, `decoded:`, `bad input:`.