0
2

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 3 years have passed since last update.

UTF-8の文字列のバイト列を取得する

Posted at

基本的なことですが、「あ」をUTF-8で表現すると 0xE3 0x81 0x82 となります。エンジニアの皆さんならこの程度は暗記しているでしょうが、私はどうも記憶力が鈍ってきたので忘れがちです。

というわけで、任意の文字列(ここでは「あいう」とします)をUTF-8で表現したときのバイト列を16進数で取得する方法について、思い付くものを適当にまとめました。実用性があるものもないものも含め、何か他にあるようでしたらコメントで教えてください。

Ruby

"あいう".unpack("H*") # ["e38182e38184e38186"]

Python3

"あいう".encode() # b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86'

JavaScript

encodeURIComponent("あいうABC") // '%E3%81%82%E3%81%84%E3%81%86ABC'

encodeURIComponent() はUTF-8を使うと規定されているのでこれが使えます。ただしASCII文字の大半はそのまま出てきます。

PowerShell

> [System.Text.Encoding]::UTF8.GetBytes("あいう") | % { "{0:x}" -f $_ }
e3
81
82
e3
81
84
e3
81
86

その他

$ echo 'あいう' | od -t x1
0000000 e3 81 82 e3 81 84 e3 81 86 0a
0000012

環境依存かもしれません(自信がありません)

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?