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

Pythonのbytesの使い方色々

Last updated at Posted at 2020-08-25

bytesの使い方

Python 3.7.5 で確認。

bytesの自力入力

b'\x00\x01\x02\x03'
# result: b'\x00\x01\x02\x03'

b'\x64\x65\x66\x67'
# result: b'defg' # asciiコードに対応した文字が表示されている

ファイルからbytesで読込


# with無し
fp = open('filename.bin', 'rb')
all_bytes = fp.read()
fp.close()

# with付き
with open('filename.bin', 'rb') as fp:
    all_bytes = fp.read()

bytesの部分切出し

a = b'\x00\x01\x02\x03' # 準備コード
a[1:3]  # listなのでlistと同じ要領でスライスが可能
# result: b'\x01\x02'

整数をbytesへ変換

a = 255  # 準備コード
a.to_bytes(2, 'little')  # to_bytes(変換後のバイト数, エンディアン)
# result: b'\xff\x00'

bytesから整数へ

a = 255                         # 準備コード
byts = a.to_bytes(2, 'little')  # 準備コード
int.from_bytes(byts, 'little')  # int.from_bytes(bytes, エンディアン)
# result: 255

bytesから整数へ(符号付き)

a = -255                                     # 準備コード
byts = a.to_bytes(2, 'little', signed=True)  # 準備コード
int.from_bytes(byts, 'little', signed=True)  # int.from_bytes(bytes, エンディアン, signed=True)
# result: -255

16進表記文字列からbytesへ

bytes.fromhex('F1E2f3f4')
bytes.fromhex('F1E2 f3f4')
bytes.fromhex('F1 E2 f3 f4')
# result: b'\xf1\xe2\xf3\xf4'

bytesを16進表記文字列へ

by = bytes.fromhex('F1E2f3f4')  # 準備コード
by.hex()
# result: 'f1e2f3f4'
2
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
2
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?