func main() {
str := "测试"
utf8By := []byte(str)
gbkBy, _ := Utf8ToGbk(utf8By)
// 直接打印用string转类型的gkb字节数组,会乱码
fmt.Println("打印GBK", string(gbkBy))
fmt.Println("UTF8字节长度: ", len(utf8By), "GBK字节长度: ", len(gbkBy))
utf8By, _ = GbkToUtf8(gbkBy)
fmt.Println("打印UTF8", string(utf8By))
return
}
// Utf8ToGbk UTF-8转GBK
func Utf8ToGbk(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
d, e := io.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
// GbkToUtf8 GBK转UTF-8
func GbkToUtf8(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
d, e := io.ReadAll(reader)
if e != nil {
return nil, e
}
return d, nil
}
执行后输出
打印GBK ����
UTF8字节长度: 6 GBK字节长度: 4
打印UTF8 测试
标签:utf8By,return,字节,nil,GBK,golang,UTF,byte
From: https://www.cnblogs.com/jing1024/p/17999576