24
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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)
}
24
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?