0
0

Pythonでのバイトデータ処理: struct.packとstruct.unpackの使い方

Posted at

はじめに

Pythonのstructモジュールは、バイトデータを扱う際に便利です。特に、C言語の構造体(struct)のようにデータをバイト列としてパック(pack)したり、バイト列からアンパック(unpack)したりする機能を提供します。

structモジュールの概要

structモジュールは、主に以下の2つの関数を提供します:

  • struct.pack(): データをバイト列に変換(パック)
  • struct.unpack(): バイト列からデータを取り出す(アンパック)

基本的な使い方

struct.packの使い方

struct.packは、指定したフォーマットに従ってデータをバイト列に変換します。

import struct

# 整数2つをバイト列にパック
packed_data = struct.pack('ii', 1, 2)
print(packed_data)  # b'\x01\x00\x00\x00\x02\x00\x00\x00'

ここで、'ii'はフォーマット文字列で、それぞれの'i'は4バイトの整数(int)を意味します。

struct.unpackの使い方

struct.unpackは、指定したフォーマットに従ってバイト列からデータを取り出します。

import struct

# バイト列を整数2つにアンパック
unpacked_data = struct.unpack('ii', packed_data)
print(unpacked_data)  # (1, 2)

フォーマット文字列の詳細

フォーマット文字列は、データの型とサイズを指定するために使用します。以下に主なフォーマット文字列を示します:

  • 'x': パディングバイト(1バイト)
  • 'c': char(1バイト)
  • 'b': signed char(1バイト)
  • 'B': unsigned char(1バイト)
  • '?': _Bool(1バイト)
  • 'h': short(2バイト)
  • 'H': unsigned short(2バイト)
  • 'i': int(4バイト)
  • 'I': unsigned int(4バイト)
  • 'l': long(4バイト)
  • 'L': unsigned long(4バイト)
  • 'q': long long(8バイト)
  • 'Q': unsigned long long(8バイト)
  • 'f': float(4バイト)
  • 'd': double(8バイト)
  • 's': char[](文字列)
  • 'p': パスカル文字列
  • 'P': voidポインタ

エンディアンの指定

エンディアン(バイトの並び順)は、フォーマット文字列の最初に指定できます。

  • '@': ネイティブエンディアン、ネイティブサイズ(デフォルト)
  • '=': ネイティブエンディアン、標準サイズ
  • '<': リトルエンディアン、標準サイズ
  • '>': ビッグエンディアン、標準サイズ
  • '!': ネットワーク(ビッグエンディアン)、標準サイズ

例:

import struct

# リトルエンディアンで整数をパック
packed_data = struct.pack('<ii', 1, 2)
print(packed_data)  # b'\x01\x00\x00\x00\x02\x00\x00\x00'

# ビッグエンディアンで整数をパック
packed_data = struct.pack('>ii', 1, 2)
print(packed_data)  # b'\x00\x00\x00\x01\x00\x00\x00\x02'

実際の例

例えば、座標データ(x, y, z)をバイト列として保存したい場合:

import struct

# 座標データをパック
x, y, z = 10, 20, 30
packed_data = struct.pack('iii', x, y, z)
print(packed_data)  # b'\n\x00\x00\x00\x14\x00\x00\x00\x1e\x00\x00\x00'

# パックしたデータをアンパック
unpacked_data = struct.unpack('iii', packed_data)
print(unpacked_data)  # (10, 20, 30)
0
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
0
0