文本主要针对utf8模块的EncodeRune
和AppendRune
两种方法的使用做了演示
使用EncodeRune对单个字符串编码的转化
注意点是,utf8编码的字符串他的字节数不是固定的,在最后转换为字符串的时候,使用变量n来确定它的字节长度,否则输出会有乱码。
// TranlateHexToUtf8 utf8编码转字符串
func TranslateHexToUtf8(hex int32) string {
switch {
case (0 <= hex && hex < utf8.RuneSelf) || hex == utf8.RuneError || !utf8.ValidRune(hex):
return ""
default:
var b [utf8.UTFMax]byte
n := utf8.EncodeRune(b[:], hex)
return string(b[:n])
}
}
使用AppendRune批量转换字符编码
// TranslateBatchHexToUtf8 utf8编码批量转字符串
func BatchTranslateHexToUtf8(hexs ...int32) (string, error) {
var (
content []byte
errCode []string
)
for _, h := range hexs {
switch {
case (0 <= h && h < utf8.RuneSelf) || h == utf8.RuneError || !utf8.ValidRune(h):
errCode = append(errCode, fmt.Sprintf("%x", h))
default:
content = utf8.AppendRune(content, h)
}
}
if len(errCode) > 0 {
return string(content), errors.New(fmt.Sprintf("Invalid utf8 code:[%v]", strings.Join(errCode, ",")))
}
return string(content), nil
}