Go GBK 字节流转字符串
package main
import (
"bytes"
"encoding/hex"
"fmt"
"io/ioutil"
"github.com/axgle/mahonia"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
)
// BytesFixString []byte 去除空数据(0), (ASCII)再转成 string. 防止溢出
func BytesFixString(origin []byte) string {
index := bytes.IndexByte(origin, 0)
if index == -1 {
return string(origin[0:])
}
return string(origin[0:index])
}
// BytesCharString []byte 转 string
func BytesCharString(value []byte, decodes ...string) string {
decode := "gbk"
if len(decodes) > 0 {
decode = decodes[0]
}
return mahonia.NewDecoder(decode).ConvertString(BytesFixString(value))
}
// UTF8ToGBK UTF8ToGBK
func UTF8ToGBK(s []byte) ([]byte, error) {
reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
return ioutil.ReadAll(reader)
}
func main() {
// value, _ := hex.DecodeString("d4c1423838383838")
value, _ := UTF8ToGBK([]byte("粤B88888"))
fmt.Printf("value hex: %s\n", hex.EncodeToString(value))
fmt.Printf("value: %s\n", BytesCharString(value))
}
=> "粤B88888"