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.
Code
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
XOR Text EncoderXOR UTF-8 text bytes with a repeating key and output hex, with full decode back to the original text.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.