いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Pythonメモ-87 (文字列から16進とか2進に変換したり戻したり)(bitstring使用)

概要

いつも忘れてしまう文字列から16進数にしたり2進数にしたりのメモ。

前に似たようなものを記事で書いた記憶があるけど、それすらも見つけることが出来なかったので。。。。

環境設定

いろいろやり方はありますが、最近こういうのは bitstring さん使ったほうが楽なので bitstring つかったサンプルです。

github.com

$ python3 -m venv sample
$ source ./sample/bin/activate
(sample) $ python -m pip install --upgrade pip
(sample) $ python -m pip install bitstring

サンプル

"""
文字列を16進数に変換するサンプルです。
bitstring を利用します。

参考URL: http://bit.ly/2VllbxA, http://bit.ly/2EyyQfm
"""
from datetime import date

from bitstring import BitArray

from common.commoncls import SampleBase
from common.commonfunc import pr


class Sample(SampleBase):
    def exec(self):
        message = f'Hello World at {date.today()}'
        message_bytes = bytes(message, encoding='utf-8')

        bit_array = BitArray(bytes=message_bytes)

        pr('original', message)
        pr('\t==> hex      ', bit_array.hex)
        pr('\t==> bin      ', bit_array.bin)
        pr('\t==> bytes    ', bit_array.tobytes())
        pr('\t==> str      ', str(bit_array.tobytes(), encoding='utf-8'))
        pr('\t==> length   ', bit_array.length // 8)
        pr('\t==> 1st byte ', bit_array[:8].tobytes())
        pr('\t==> 2nd byte ', bit_array[8:8 * 2].tobytes())
        pr('\t==> last byte', bit_array[-8:].tobytes())


def go():
    obj = Sample()
    obj.exec()


if __name__ == '__main__':
    go()

結果は以下のようになります。

(sample) $ python -m trypython.advanced.str_to_hex_or_bin01
original='Hello World at 2019-02-28'
    ==> hex      ='48656c6c6f20576f726c6420617420323031392d30322d3238'
    ==> bin      ='01001000011001010110110001101100011011110010000001010111011011110111001001101100011001000010000001100001011101000010000000110010001100000011000100111001001011010011000000110010001011010011001000111000'
    ==> bytes    =b'Hello World at 2019-02-28'
    ==> str      ='Hello World at 2019-02-28'
    ==> length   =25
    ==> 1st byte =b'H'
    ==> 2nd byte =b'e'
    ==> last byte=b'8'

try-python/str_to_hex_or_bin01.py at master · devlights/try-python · GitHub


過去の記事については、以下のページからご参照下さい。

  • いろいろ備忘録日記まとめ

devlights.github.io

サンプルコードは、以下の場所で公開しています。

  • いろいろ備忘録日記サンプルソース置き場

github.com

github.com