golang gbk utf-8 相互转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"bytes"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io/ioutil"
"fmt"
)
func GbkToUtf8(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
d, e := ioutil.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
func Utf8ToGbk(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
d, e := ioutil.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
func main() {
s := "GBK 与 UTF-8 编码转换测试"
gbk, err := Utf8ToGbk([]byte(s))
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(gbk))
}
utf8, err := GbkToUtf8(gbk)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(utf8))
}
}
本文网址: https://golangnote.com/topic/147.html 转摘请注明来源