3
0

More than 1 year has passed since last update.

MicroPythonで16進数のバイト文字列(bytes型)を文字列(str型)に変換

Last updated at Posted at 2022-06-23

16進数のバイト文字列の変換

MicroPythonで16進数のバイト文字列(bytes型)を文字列(str型)に変換する。
@inachi 様、変換方法を教えていただ気ありがとうございます。)

変換例
b'6170706c65'   "apple"
b'6364736c'     "cdsl"
b'61626364'     "abcd"
b'31323334'     "1234"

ESP32でBLEの実装作業【スキャン】を参考にして、データ部に格納した文字を取り出そうとした所、16進数のバイト文字列だった。文字列(str型)に変換して、人間が読める状態にしたい。

MicroPythonで苦戦

インターネットで検索するとbytes.fromhexを使う方法が出てきた。
Tech Blog - プログラミングに関しての備忘録

Python 3.9.0
>>> hex_bytes = b'6170706c65'
>>> hex_str = hex_bytes.decode("utf-8")
>>> print(bytes.fromhex(hex_str).decode('utf-8'))
apple

このコードをMicroPythonで実行する。

MicroPython v1.18
>>> hex_bytes = b'6170706c65'
>>> hex_str = hex_bytes.decode("utf-8")
>>> print(bytes.fromhex(hex_str).decode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'bytes' has no attribute 'fromhex'

Python3では実行できたが、MicroPythonではエラーが出てしまった。

関数の作成

代わりにMicroPythonで使用できる関数を作成した。
( ↑関数を作る必要なんてなかった )

関数
def hex_bytes_to_str(hex_bytes):
    hex_str = hex_bytes.decode()

    return_str = ""
    for i in range(0, len(hex_str), 2):
        char_hex = hex_str[i] + hex_str[i+1]
        return_str+= chr(int(char_hex, 16))

    return return_str
MicroPython v1.18
>>> hex_bytes = b'6170706c65'
>>> print(hex_bytes_to_str(hex_bytes))
apple

組み込み関数で変換

コメントで @inachi 様より変換方法を教えていただいた。
教えていただきありがとうございます。

MicroPython v1.18
>>> import binascii
>>> hex_bytes = b'6170706c65'
>>> print(str(binascii.unhexlify(hex_bytes), 'utf-8'))
apple

これで良し。

3
0
2

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