15
6

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 で文字列と16進数の相互変換

Last updated at Posted at 2017-10-02

REPL

REPL として gore を利用します。起動は次のコマンドです。

gore

次のパッケージをあらかじめ導入します。

go get -u github.com/motemen/gore
go get -u github.com/nsf/gocode
go get -u github.com/k0kubun/pp
go get -u golang.org/x/tools/cmd/godoc

文字列とバイト列の相互変換

> []byte("あ")
[]uint8{
  0xe3, 0x81, 0x82,
}
> []byte("\xe3\x81\x82")
[]uint8{
  0xe3, 0x81, 0x82,
}
> string([]byte{0xe3, 0x81, 0x82})
"あ"
> string([]byte{'\xe3', '\x81', '\x82'})
"あ"

文字とコードポイントの相互変換

文字を rune の配列に変換することでコードポイントを求めることができます。

> :import fmt
> r := []rune("あ")
[]int32{
  12354,
}
> r[0]
12354
> fmt.Sprintf("%x", r[0])
"3042"
> string([]rune{0x3042})
"あ"

コードポイントからバイト列の相互変換をするには一度文字列に変換する必要があります。

> []byte(string([]rune{0x3042}))
[]uint8{
  0xe3, 0x81, 0x82,
}
> []rune(string([]byte{0xe3, 0x81, 0x82}))
[]int32{
  12354,
}

文字列と16進数文字列の相互変換

> :import encoding/hex
> hex.EncodeToString([]byte("あ"))
"e38182"
> ret, _ := hex.DecodeString("e38182")
[]uint8{
  0xe3, 0x81, 0x82,
}
> string(ret)
"あ"

hexdump -C と同じ結果になります。

> hex.Dump([]byte("あ"))
"00000000  e3 81 82                                          |...|\n"

整数と16進数文字列の相互変換

> :import strconv
> strconv.FormatInt(0xe38182, 16)
"e38182"
> strconv.ParseInt("e38182", 16, 32)
14909826
nil
gore> 0xe38182
14909826

strconv.FormatInt の代わりに fmt.Sprintf を使うこともできます。

> :import fmt
> fmt.Sprintf("%x", 0xe38182)
"e38182"

整数とバイト列の相互変換

前述の結果をもとに整数とバイト列の相互変換することができます。

> ret, _ := hex.DecodeString(strconv.FormatInt(0xe38182, 16))
[]uint8{
  0xe3, 0x81, 0x82,
}
> string(ret)
"あ"
> strconv.ParseInt(hex.EncodeToString([]byte{0xe3, 0x81, 0x82}), 16, 32)
14909826
nil
> 0xe38182
14909826

UTF-8 とレガシーエンコーディングの相互変換

go get -v golang.org/x/text/encoding/japanese
go get -v golang.org/x/text/transform

それぞれのエンコーディングごとに定義される NewEncoder、NewDecoder を呼び出します。

> :import golang.org/x/text/encoding/japanese
> :import golang.org/x/text/transform
> transform.String(japanese.ShiftJIS.NewEncoder(), "あ")
"\x82\xa0"
3
nil
> transform.String(japanese.ShiftJIS.NewDecoder(), "\x82\xa0")
"あ"
2
nil

Shift_JIS のバイト列をあらわす整数を UTF-8 の文字列に変換してみましょう。

> ret, _ := hex.DecodeString(strconv.FormatInt(0x82a0, 16))
[]uint8{
  0x82, 0xa0,
}
> string(ret)
"\x82\xa0"
> transform.String(japanese.ShiftJIS.NewDecoder(), string(ret))
"あ"
2
nil
15
6
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
15
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?