Help us understand the problem. What is going on with this article?

GO言語で文字コードを扱うライブラリの使用例

More than 5 years have passed since last update.

Go言語でSJISの文字列を扱う機会があったので,文字コードを扱うライブラリをいくつか使ってみました.

今回使用したライブラリ

iconv-go

cgoが必要です.

import (
    "fmt"
    iconv "github.com/djimenez/iconv-go"
)

func main() {
    // sjis string
    data := []byte{0x47, 0x4f, 0x8c, 0xbe, 0x8c, 0xea}
    in := string(data[:])

    // iconv-go
    result, err := iconv.ConvertString(in, "sjis", "utf-8")
    if err != nil {
        panic(err)
    }

    fmt.Printf("%v\n", result)
}

go-charset

内部でGNU iconvを使用してます.

import (
    charset "code.google.com/p/go-charset/charset"
    _ "code.google.com/p/go-charset/data"
    "fmt"
    "io/ioutil"
    "strings"
)

func main() {
    // sjis string
    data := []byte{0x47, 0x4f, 0x8c, 0xbe, 0x8c, 0xea}
    in := string(data[:])

    // go-charset
    out, err := charset.NewReader("cp932", strings.NewReader(in))
    if err != nil {
        panic(err)
    }
    result, err := ioutil.ReadAll(out)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%v\n", string(result[:]))
}

mahonia

iconv-goやgo-charsetと違い,iconvを使ってないのでクロスコンパイルが容易です.

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

func main() {
    // sjis string
    data := []byte{0x47, 0x4f, 0x8c, 0xbe, 0x8c, 0xea}
    in := string(data[:])

    // mahonia
    result := mahonia.NewDecoder("cp932").ConvertString(in)

    fmt.Printf("%v\n", result)
}
irugo
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした