LoginSignup
0
0

More than 1 year has passed since last update.

Python v2.7でバイナリデータ解析

Last updated at Posted at 2022-04-10

バイナリデータを解析したい

アプリケーションの管理データはバイナリファイルになっていることが多々あります。
そんなデータの中身をテキスト表示して確認したいと思ったのが始まりです。

実行環境

アプリケーションの実行環境がLinuxでPython2.7がインストールされていて、バージョンアップが難しいので、今回はPython 2.7を実行環境とします。

$ python --version
Python 2.7.5

バイナリデータ解析のクラス作成

まずはサンプルコード。

test.py
 class MyData:
     column1 = ""  # カラム1
     column2 = ""  # カラム2
     column3 = ""  # カラム3

     def __init__(self, data):
         with io.BytesIO(data) as buffer:
             self.column1 = struct.unpack('<H', buffer.read(2))[0]
             self.column2 = struct.unpack('<L', buffer.read(4))[0]
             self.column3 = struct.unpack('<Q', buffer.read(8))[0]

unpackの型指定の意味は下記。他の指定方法はdocsにあります。

 "<" : リトルエンディアン
  "H" : unsigned short /2byte
  "L" : unsigned long  /4byte
  "Q" : unsigned long long  /8byte
 tuple型となり、[0]で1つ目の要素を参照

インスタンスにデータを取り込んで、メンバ変数を参照することで表示できます。

test.py
my_data = MYData(data)
print("column1: " + str(my_data.column1))
print("column2: " + str(my_data.column2))
print("column3: " + str(my_data.column3))

参照

7.3. struct — Interpret strings as packed binary data
https://docs.python.org/2.7/library/struct.html#format-strings

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