encoding/hex
最後更新
encoding/hex 把位元組轉成十六進位字串(例如 0x4f 變成 "4f"),也能反過來解析,還能印出類似 hexdump 的除錯畫面。這個套件做什麼
一個位元組有 256 種可能值,用十六進位表示剛好是兩個字元(
00 到 ff)。十六進位字串最常出現在:- 雜湊值:SHA-256 的結果通常印成 64 個十六進位字元,見 crypto/sha256
- 隨機 token、識別碼:用 crypto/rand 產生位元組後轉成十六進位
- 除錯:查看檔案或網路封包的原始位元組
和 encoding/base64 比較:
| hex | base64 | |
|---|---|---|
| 長度 | 原本的 2 倍 | 約 4/3 倍 |
| 字元 | 0-9 a-f | 英數字與 +/ 或 -_ |
| 優點 | 人眼容易對照每個位元組 | 比較短 |
另外,
fmt.Sprintf("%x", b) 也能把位元組印成十六進位,簡單印出時可以直接用 fmt;需要解析、串流或 dump 格式時才用 encoding/hex。匯入
- import "encoding/hex"
常用 API
hex.EncodeToString
把
[]byte 轉成小寫十六進位字串,長度是原本的 2 倍。簽名:
- func EncodeToString(src []byte) string
範例:
- package main
- import (
- "crypto/sha256"
- "encoding/hex"
- "fmt"
- )
- func main() {
- fmt.Println(hex.EncodeToString([]byte("Go")))
- fmt.Println(hex.EncodeToString([]byte{0, 15, 16, 255}))
- sum := sha256.Sum256([]byte("hello"))
- fmt.Println(hex.EncodeToString(sum[:]))
- }
輸出:
- 476f
- 000f10ff
- 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
hex.DecodeString
把十六進位字串解回位元組,大小寫都接受。
簽名:
- func DecodeString(s string) ([]byte, error)
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- )
- func main() {
- b, err := hex.DecodeString("48656C6C6f")
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println(string(b), b)
- _, err = hex.DecodeString("abc")
- fmt.Println(err)
- _, err = hex.DecodeString("zz")
- fmt.Println(err)
- }
輸出:
- Hello [72 101 108 108 111]
- encoding/hex: odd length hex string
- encoding/hex: invalid byte: U+007A 'z'
注意:長度是奇數時回傳
hex.ErrLength;含有非十六進位字元時回傳 hex.InvalidByteError,它的值就是那個無效字元。hex.Encode 與 hex.Decode
寫進你自己準備的切片,不配置新字串。
EncodedLen(n) 是 n*2,DecodedLen(n) 是 n/2,用來決定目的切片長度。回傳值是實際寫入的位元組數。簽名:
- func Encode(dst, src []byte) int
- func Decode(dst, src []byte) (int, error)
- func EncodedLen(n int) int
- func DecodedLen(x int) int
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- )
- func main() {
- src := []byte{0xca, 0xfe}
- dst := make([]byte, hex.EncodedLen(len(src)))
- n := hex.Encode(dst, src)
- fmt.Println(n, string(dst))
- out := make([]byte, hex.DecodedLen(len(dst)))
- n, err := hex.Decode(out, dst)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Printf("%d % x\n", n, out)
- }
輸出:
- 4 cafe
- 2 ca fe
注意:
dst 太短時 Encode 與 Decode 會 panic(索引超出範圍)。hex.AppendEncode 與 hex.AppendDecode
Go 1.22 起,把結果附加到既有切片後面並回傳新切片,用法和內建的
append 一樣,不用自己算長度。簽名:
- func AppendEncode(dst, src []byte) []byte
- func AppendDecode(dst, src []byte) ([]byte, error)
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- )
- func main() {
- line := []byte("id=")
- line = hex.AppendEncode(line, []byte{0x01, 0xab, 0xff})
- fmt.Println(string(line))
- raw, err := hex.AppendDecode(nil, line[len("id="):])
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println(raw)
- }
輸出:
- id=01abff
- [1 171 255]
hex.Dump
把位元組排成「位移、十六進位、可列印字元」三欄的格式,每行 16 個位元組,和 Unix 的
hexdump -C 很像。除錯二進位檔案或網路協定時非常好用。簽名:
- func Dump(data []byte) string
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- )
- func main() {
- data := []byte("Hello, Gopher!\n\x00\x01\x02 binary")
- fmt.Print(hex.Dump(data))
- }
輸出:
- 00000000 48 65 6c 6c 6f 2c 20 47 6f 70 68 65 72 21 0a 00 |Hello, Gopher!..|
- 00000010 01 02 20 62 69 6e 61 72 79 |.. binary|
右欄中不可列印的位元組(換行、
0x00 等)會顯示成 .。hex.Dumper
Dump 需要整份資料在記憶體;Dumper 是串流版本,回傳一個 io.WriteCloser,寫進去的資料會以 dump 格式輸出到底層 writer。寫完要 Close,才會補齊最後一行的右欄。適合搭配 io.Copy 檢視大檔案,見 io。簽名:
- func Dumper(w io.Writer) io.WriteCloser
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- "io"
- "os"
- "strings"
- )
- func main() {
- d := hex.Dumper(os.Stdout)
- if _, err := io.Copy(d, strings.NewReader("streaming 資料 OK!")); err != nil {
- fmt.Println("error:", err)
- return
- }
- d.Close()
- }
輸出:
- 00000000 73 74 72 65 61 6d 69 6e 67 20 e8 b3 87 e6 96 99 |streaming ......|
- 00000010 20 4f 4b 21 | OK!|
hex.NewEncoder 與 hex.NewDecoder
NewEncoder 包裝 io.Writer,寫進去的位元組被轉成十六進位文字輸出;NewDecoder 包裝 io.Reader,讀出來的是解碼後的位元組。用於串流處理,不必一次載入全部資料。簽名:
- func NewEncoder(w io.Writer) io.Writer
- func NewDecoder(r io.Reader) io.Reader
範例:
- package main
- import (
- "encoding/hex"
- "fmt"
- "io"
- "strings"
- )
- func main() {
- var sb strings.Builder
- w := hex.NewEncoder(&sb)
- w.Write([]byte("abc"))
- w.Write([]byte{0x00, 0xff})
- fmt.Println(sb.String())
- r := hex.NewDecoder(strings.NewReader(sb.String()))
- data, err := io.ReadAll(r)
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Printf("%q\n", data)
- }
輸出:
- 61626300ff
- "abc\x00\xff"
重點整理
- 十六進位字串長度是原始位元組的 2 倍,常用來顯示雜湊值、token 與除錯
- 日常用
EncodeToString/DecodeString;Go 1.22 起可用AppendEncode/AppendDecode - 解碼失敗分兩種:奇數長度
ErrLength、非法字元InvalidByteError - 自己配置緩衝區時用
EncodedLen/DecodedLen,太短會 panic - 除錯時用
Dump(整份資料)或Dumper(串流)印出 hexdump 格式