Home > Backend Development > Golang > How to Convert Text from Windows-1256 to UTF-8 in Go?

How to Convert Text from Windows-1256 to UTF-8 in Go?

Mary-Kate Olsen
Release: 2024-11-29 16:43:18
Original
159 people have browsed it

How to Convert Text from Windows-1256 to UTF-8 in Go?

Encoding Text in Go

When working with text data, it is often necessary to convert between different encodings. UTF-8 is a widely used encoding that is capable of representing a wide range of characters.

Question: How do you convert text from an encoding such as Windows-1256 Arabic to UTF-8 in Go?

Answer:

To perform this conversion, utilize the encoding package available in Go. Additionally, the golang.org/x/text/encoding/charmap package provides support for various encodings, including Windows-1256.

Example:

The following code snippet demonstrates how to encode text from Japanese UTF-8 to ShiftJIS and subsequently decode it back to UTF-8:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "strings"

    "golang.org/x/text/encoding/japanese"
    "golang.org/x/text/transform"
)

func main() {
    // Input string
    s := "今日は"
    fmt.Println(s)

    // Encode: Convert s from UTF-8 to ShiftJIS
    var b bytes.Buffer
    wInUTF8 := transform.NewWriter(&b, japanese.ShiftJIS.NewEncoder())
    wInUTF8.Write([]byte(s))
    wInUTF8.Close()
    encodedBytes := b.Bytes()
    fmt.Printf("%#v\n", encodedBytes)
    encS := string(encodedBytes)
    fmt.Println(encS)

    // Decode: Convert encodedBytes from ShiftJIS to UTF-8
    rInUTF8 := transform.NewReader(strings.NewReader(encS), japanese.ShiftJIS.NewDecoder())
    decodedBytes, _ := ioutil.ReadAll(rInUTF8)
    decodedString := string(decodedBytes)
    fmt.Println(decodedString)
}
Copy after login

For a more comprehensive example, refer to the following link: https://ja.stackoverflow.com/questions/6120.

The above is the detailed content of How to Convert Text from Windows-1256 to UTF-8 in Go?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template