encoding/hex

最後更新


encoding/hex 把位元組轉成十六進位字串(例如 0x4f 變成 "4f"),也能反過來解析,還能印出類似 hexdump 的除錯畫面。

這個套件做什麼


一個位元組有 256 種可能值,用十六進位表示剛好是兩個字元(00 到 ff)。十六進位字串最常出現在:
  • 雜湊值:SHA-256 的結果通常印成 64 個十六進位字元,見 crypto/sha256
  • 隨機 token、識別碼:用 crypto/rand 產生位元組後轉成十六進位
  • 除錯:查看檔案或網路封包的原始位元組

和 encoding/base64 比較:
hexbase64
長度原本的 2 倍約 4/3 倍
字元0-9 a-f英數字與 +/ 或 -_
優點人眼容易對照每個位元組比較短

另外,fmt.Sprintf("%x", b) 也能把位元組印成十六進位,簡單印出時可以直接用 fmt;需要解析、串流或 dump 格式時才用 encoding/hex。

匯入


  1. import "encoding/hex"

常用 API


hex.EncodeToString


把 []byte 轉成小寫十六進位字串,長度是原本的 2 倍。
簽名:
  1. func EncodeToString(src []byte) string

範例:
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. func main() {
  8. fmt.Println(hex.EncodeToString([]byte("Go")))
  9. fmt.Println(hex.EncodeToString([]byte{0, 15, 16, 255}))
  10. sum := sha256.Sum256([]byte("hello"))
  11. fmt.Println(hex.EncodeToString(sum[:]))
  12. }

輸出:
  1. 476f
  2. 000f10ff
  3. 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

hex.DecodeString


把十六進位字串解回位元組,大小寫都接受。
簽名:
  1. func DecodeString(s string) ([]byte, error)

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. b, err := hex.DecodeString("48656C6C6f")
  8. if err != nil {
  9. fmt.Println("error:", err)
  10. return
  11. }
  12. fmt.Println(string(b), b)
  13. _, err = hex.DecodeString("abc")
  14. fmt.Println(err)
  15. _, err = hex.DecodeString("zz")
  16. fmt.Println(err)
  17. }

輸出:
  1. Hello [72 101 108 108 111]
  2. encoding/hex: odd length hex string
  3. encoding/hex: invalid byte: U+007A 'z'

注意:長度是奇數時回傳 hex.ErrLength;含有非十六進位字元時回傳 hex.InvalidByteError,它的值就是那個無效字元。

hex.Encode 與 hex.Decode


寫進你自己準備的切片,不配置新字串。EncodedLen(n) 是 n*2,DecodedLen(n) 是 n/2,用來決定目的切片長度。回傳值是實際寫入的位元組數。
簽名:
  1. func Encode(dst, src []byte) int
  2. func Decode(dst, src []byte) (int, error)
  3. func EncodedLen(n int) int
  4. func DecodedLen(x int) int

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. src := []byte{0xca, 0xfe}
  8. dst := make([]byte, hex.EncodedLen(len(src)))
  9. n := hex.Encode(dst, src)
  10. fmt.Println(n, string(dst))
  11. out := make([]byte, hex.DecodedLen(len(dst)))
  12. n, err := hex.Decode(out, dst)
  13. if err != nil {
  14. fmt.Println("error:", err)
  15. return
  16. }
  17. fmt.Printf("%d % x\n", n, out)
  18. }

輸出:
  1. 4 cafe
  2. 2 ca fe

注意:dst 太短時 Encode 與 Decode 會 panic(索引超出範圍)。

hex.AppendEncode 與 hex.AppendDecode


Go 1.22 起,把結果附加到既有切片後面並回傳新切片,用法和內建的 append 一樣,不用自己算長度。
簽名:
  1. func AppendEncode(dst, src []byte) []byte
  2. func AppendDecode(dst, src []byte) ([]byte, error)

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. line := []byte("id=")
  8. line = hex.AppendEncode(line, []byte{0x01, 0xab, 0xff})
  9. fmt.Println(string(line))
  10. raw, err := hex.AppendDecode(nil, line[len("id="):])
  11. if err != nil {
  12. fmt.Println("error:", err)
  13. return
  14. }
  15. fmt.Println(raw)
  16. }

輸出:
  1. id=01abff
  2. [1 171 255]

hex.Dump


把位元組排成「位移、十六進位、可列印字元」三欄的格式,每行 16 個位元組,和 Unix 的 hexdump -C 很像。除錯二進位檔案或網路協定時非常好用。
簽名:
  1. func Dump(data []byte) string

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. )
  6. func main() {
  7. data := []byte("Hello, Gopher!\n\x00\x01\x02 binary")
  8. fmt.Print(hex.Dump(data))
  9. }

輸出:
  1. 00000000 48 65 6c 6c 6f 2c 20 47 6f 70 68 65 72 21 0a 00 |Hello, Gopher!..|
  2. 00000010 01 02 20 62 69 6e 61 72 79 |.. binary|

右欄中不可列印的位元組(換行、0x00 等)會顯示成 .。

hex.Dumper


Dump 需要整份資料在記憶體;Dumper 是串流版本,回傳一個 io.WriteCloser,寫進去的資料會以 dump 格式輸出到底層 writer。寫完要 Close,才會補齊最後一行的右欄。適合搭配 io.Copy 檢視大檔案,見 io。
簽名:
  1. func Dumper(w io.Writer) io.WriteCloser

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io"
  6. "os"
  7. "strings"
  8. )
  9. func main() {
  10. d := hex.Dumper(os.Stdout)
  11. if _, err := io.Copy(d, strings.NewReader("streaming 資料 OK!")); err != nil {
  12. fmt.Println("error:", err)
  13. return
  14. }
  15. d.Close()
  16. }

輸出:
  1. 00000000 73 74 72 65 61 6d 69 6e 67 20 e8 b3 87 e6 96 99 |streaming ......|
  2. 00000010 20 4f 4b 21 | OK!|

hex.NewEncoder 與 hex.NewDecoder


NewEncoder 包裝 io.Writer,寫進去的位元組被轉成十六進位文字輸出;NewDecoder 包裝 io.Reader,讀出來的是解碼後的位元組。用於串流處理,不必一次載入全部資料。
簽名:
  1. func NewEncoder(w io.Writer) io.Writer
  2. func NewDecoder(r io.Reader) io.Reader

範例:
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io"
  6. "strings"
  7. )
  8. func main() {
  9. var sb strings.Builder
  10. w := hex.NewEncoder(&sb)
  11. w.Write([]byte("abc"))
  12. w.Write([]byte{0x00, 0xff})
  13. fmt.Println(sb.String())
  14. r := hex.NewDecoder(strings.NewReader(sb.String()))
  15. data, err := io.ReadAll(r)
  16. if err != nil {
  17. fmt.Println("error:", err)
  18. return
  19. }
  20. fmt.Printf("%q\n", data)
  21. }

輸出:
  1. 61626300ff
  2. "abc\x00\xff"

重點整理


  • 十六進位字串長度是原始位元組的 2 倍,常用來顯示雜湊值、token 與除錯
  • 日常用 EncodeToString/DecodeString;Go 1.22 起可用 AppendEncode/AppendDecode
  • 解碼失敗分兩種:奇數長度 ErrLength、非法字元 InvalidByteError
  • 自己配置緩衝區時用 EncodedLen/DecodedLen,太短會 panic
  • 除錯時用 Dump(整份資料)或 Dumper(串流)印出 hexdump 格式

資料來源