GolangNote

Golang笔记

golang gbk utf-8 相互转换

Permalink

golang gbk utf-8 相互转换

golang gbk utf-8 相互转换

Go: 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))
    }
}

Related articles

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

Write a Comment to "golang gbk utf-8 相互转换"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms