2025-10-22

Go 進行編碼轉換

GoLang 可以使用 https://pkg.go.dev/golang.org/x/text/encoding#Encoding 進行編碼轉換

Encoding 的架構如下

type encoding.Encoding interface {
	// NewDecoder returns a Decoder.
	NewDecoder() *encoding.Decoder

	// NewEncoder returns an Encoder.
	NewEncoder() *encoding.Encoder
}

其中,Encoder 是負責將 UTF-8 轉為指定編碼;Decoder 則是將指定編碼轉為 UTF-8。

Encoding interface 在其子 package 已經有許多完成的實作,例如 golang.org/x/text/encoding/traditionalchinese 有 Big5 的 Encoding;golang.org/x/text/encoding/japanese 有 ShiftJIS 的 Encoding……等等


例如將 UTF-8 轉為 Big5:

package main

import (
	"fmt"
	"log"

	"golang.org/x/text/encoding/traditionalchinese"
)

func main() {
	origBytes := []byte("你好,世界")
	fmt.Println(origBytes)
	big5Bytes, err := traditionalchinese.Big5.NewEncoder().Bytes(origBytes)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(big5Bytes) 
}

上面這段程式,可以將輸入的字串"你好,世界",轉為 big5 編碼的 byte slice

輸出的結果如下

Original Bytes: [228 189 160 229 165 189 239 188 140 228 184 150 231 149 140]
Big5 Bytes    : [167 65 166 110 161 65 165 64 172 201]

範例

如果想要將 Big5 轉為 UTF-8 的話

package main

import (
	"fmt"
	"log"

	"golang.org/x/text/encoding/traditionalchinese"
)

func main() {
	big5Bytes := []byte{byte(167), byte(65), byte(166), byte(110), byte(161), byte(65), byte(165), byte(64), byte(172), byte(201)}

	utf8Bytes, err := traditionalchinese.Big5.NewDecoder().Bytes(big5Bytes)

	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Result (bytes):", utf8Bytes)
	fmt.Println("Result        :", string(utf8Bytes))
}

回傳結果:

Result (bytes): [228 189 160 229 165 189 239 188 140 228 184 150 231 149 140]
Result        : 你好,世界

沒有留言:

張貼留言