1
0

【Python】int,bytes,strの相互変換と表示

Posted at

■ 2進数・16進数で数値を宣言する

# 2進数
n = 0b1111111111111111  # 65535

# 16進数
n = 0xffff  # 65535

■ intからbytesに変換

int -> bytes

n = 0b1111000111110010
# 2バイトでビッグエンディアン
n.to_bytes(2, 'big')  # b'\xf1\xf2'

# 2バイトでリトルエンディアン
n.to_bytes(2, 'little')  # b'\xf2\xf1'

# 4バイトでビッグエンディアン
n.to_bytes(4, 'big')  # b'\x00\x00\xf1\xf2'

# 4バイトでリトルエンディアン
n.to_bytes(4, 'little')  # b'\xf2\xf1\x00\x00'

structを使う方法

■ バイト順の指定
- < リトルエンディアン
- > ビッグエンディアン

■ データ型の指定
- b char型 (1バイト)
- B unsigned char型 (1バイト)
- h short型 (2バイト)
- H unsigned short型 (2バイト)
- i int型 (3バイト)
- I unsigned int型 (3バイト)
- l long型 (4バイト)
- L unsigned long型 (4バイト)
import struct
n = 0b1111000111110010

# 2バイト(符号なし)でビッグエンディアン
struct.pack(">H", n)  # b'\xf1\xf2'

# 4バイト(符号あり)でリトルエンディアン
struct.pack("<l", n)  # b'\xf2\xf1\x00\x00'

List[int] -> bytes

arr = [0b00000001, 0b00000011]
bytes(arr)  # b'\x01\x03'

■ bytesからintに変更

# ビッグエンディアン
int.from_bytes(b'\xf1\xf2', 'big')  # 61938
# リトルエンディアン
int.from_bytes(b'\xf2\xf1', 'little')  # 61938
# ビッグエンディアン (先頭の\x00は無視される)
int.from_bytes(b'\x00\x00\xf1\xf2', 'big')  # 61938
# リトルエンディアン (末尾の\x00は無視される)
int.from_bytes(b'\xf2\xf1\x00\x00', 'little')  # 61938

■ strからbytesに変換

str -> bytes

# str -> bytes (エンコード)
'abc123'.encode('utf-8')  # エンコーディング形式を指定する

bytes -> str

# bytes -> str (デコード)
b'abc123'.decode('utf-8')  # エンコーディング形式を指定する

# 変換できないときは UnicodeDecodeError になる
try:
    b'\x80abc'.decode('utf-8')
except UnicodeDecodeError as e:
    print(e)

■ 表示

intの表示

n = 61938

# int -> 2進数表示
bin(n)  # '0b1111000111110010'

# int -> 8進数表示
oct(n)  # '0o170762'

# int -> 16進数表示
hex(n)  # '0xf1f2'

bytesの表示

# bytes -> 16進数表示
n.to_bytes(2, 'big').hex()  # 'f1f2'
n.to_bytes(2, 'little').hex()  # 'f2f1'
n.to_bytes(4, 'big').hex()  # '0000f1f2'
n.to_bytes(4, 'little').hex()  # 'f2f10000'

自分で実装する

from typing import Union, List
def int_to_binary(n: int, bits: int = 8) -> str:
    """intを2進数に変換"""
    return ''.join([str(n >> i & 1 ) for i in reversed(range(0, bits))])

def bytes_to_binary(data: Union[bytearray,bytes]) -> List[str]:
    """bytesを2進数のリストに変換"""
    return [int_to_binary(byte) for byte in data]


# int -> 2進数表示
n = 61938
int_to_binary(n, 16)  # '1111000111110010'

# bytes -> 2進数表示
b = n.to_bytes(2, 'big')
bytes_to_binary(b)  # ['11110001', '11110010']
1
0
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
1
0