Skip to main content

gbk转utf8

gbk转utf8的库

gopm get -g -v golang.org/x/text
gopm get -g -v golang.org/x/net/html

mahonia 库

go get github.com/axgle/mahonia
  • 然后新建一个 func
  • src 字符串
  • srcCode 字符串当前编码
  • tagCode 要转换的编码
func ConvertToString(src string, srcCode string, tagCode string) string {
srcCoder := mahonia.NewDecoder(srcCode)
srcResult := srcCoder.ConvertString(src)
tagCoder := mahonia.NewDecoder(tagCode)
_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
result := string(cdata)
return result
}

例子1:

调用 ConvertToString 方法

str := "乱码的字符串变量"
str = ConvertToString(str, "gbk", "utf-8")
fmt.Println(str)

例子2:

package main

import (
"code.google.com/p/mahonia"
"fmt"
)

func main() {
//"你好,世界!"的GBK编码
testBytes := []byte{0xC4, 0xE3, 0xBA, 0xC3, 0xA3, 0xAC, 0xCA, 0xC0, 0xBD, 0xE7, 0xA3, 0xA1}
var testStr string
utfStr := "你好,世界!"
var dec mahonia.Decoder
var enc mahonia.Encoder

testStr = string(testBytes)

dec = mahonia.NewDecoder("gbk")
if ret, ok := dec.ConvertStringOK(testStr); ok {
fmt.Println("GBK to UTF-8: ", ret, " bytes:", testBytes)
}

enc = mahonia.NewEncoder("gbk")
if ret, ok := enc.ConvertStringOK(utfStr); ok {
fmt.Println("UTF-8 to GBK: ", ret, " bytes: ", []byte(ret))
}
return
}