Home > Common Problem > How to perform encoding conversion in golang

How to perform encoding conversion in golang

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-06-13 15:03:04
Original
2502 people have browsed it

The method for encoding conversion in golang is: 1. Create a Go sample file; 2. Import the "encoding" and "unicode/utf8" packages in the standard library; 3. Define a function "utf8ToGBK" to accept A UTF-8 encoded string is taken as input and a GBK encoded string is returned; 4. Call the "utf8ToGBK" function and print the result.

How to perform encoding conversion in golang

Operating system for this tutorial: Windows 10 system, Go1.20.1 version, Dell G3 computer.

For encoding conversion in Golang, you can use the `encoding` and `unicode/utf8` packages in the standard library.

The following is a simple sample code to convert UTF-8 encoded string to GBK encoding.

1. First, you need to import the following package:

import (
    "fmt"
    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
)
Copy after login

Next, we define a function `utf8ToGBK`, which accepts a UTF-8 encoded string as input and returns a GBK encoding String.

func utf8ToGBK(input string) (string, error) {
    // 将输入的UTF-8编码的字符串转换为字节数组
    inputBytes := []byte(input)
    // 定义一个transformer,将UTF-8编码转换为GBK编码
    transformer := simplifiedchinese.GBK.NewEncoder()
    // 执行转换
    outputBytes, err := transform.Bytes(transformer, inputBytes)
    if err != nil {
        return "", fmt.Errorf("convert to GBK failed: %v", err)
    }
    // 将转换后的字节数组转换回字符串
    output := string(outputBytes)
    return output, nil
}
Copy after login

Finally, we call the `utf8ToGBK` function and print the output result:

func main() {
    input := "你好,世界!"
    output, err := utf8ToGBK(input)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(output)
}
Copy after login

Run this program, the output result should be:

浣犲ソ锛嶆垜浠笂鍏?
Copy after login

Note that this string is GBK Encoded, garbled characters may appear on some monitors due to the inability to correctly parse GBK.

The above is the detailed content of How to perform encoding conversion in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template