Python バイトを整数に変換する方法
Bytes データ型の値の範囲は 0〜255(0x00〜0xFF)です。1 バイトには 8 ビットがあるため、最大値は 0xFF です。状況によっては、バイトまたはバイト配列をさらにデータ処理するために整数に変換する必要があります。この記事では、バイトを整数に変換する方法を紹介します。
Python 2.7 バイト Bytes
Python 2.7 バージョンには組み込みの bytes データ型はありません。キーワード byte は str と同じです。
>>> bytes is str
True
bytearray は bytes または byte array を定義するために使用されます。
>>> byteExample1 = bytearray([1])
>>> byteExample1
bytearray(b'\x01')
>>> byteExample2 = bytearray([1,2,3])
>>> byteExample2
bytearray(b'\x01\x02\x03')
Python 2.7 でバイトから整数への変換
Python 内部モジュール struct は、バイナリデータ(バイト)を整数に変換できます。Python 2.7 ではバイトまたは実際に文字列を、双方向では整数に変換できます。
`struct.unpack(fmt, string)`
Convert the string according to the given format `fmt` to integers. The result is a tuple even if there is only one item inside.
struct の例
import struct
testBytes = b"\x00\x01\x00\x02"
testResult = struct.unpack(">HH", testBytes)
print testResult
(1, 2)
フォーマット文字列 >HH には 2つの部分が含まれます。
>は、バイナリデータがbig-endianであることを示します。つまり、データはビッグエンド(最上位ビット)から並べられます。たとえば、\x00\0x1では\x00は上位バイトで、\x01が下位バイトです。HHは、バイト文字列にHタイプの 2つのオブジェクトがあることを意味します。Hは、2 バイトを占めるunsigned short整数であることを示します。
割り当てられたデータ形式が異なる場合、同じ文字列から異なる結果が得られる可能性があります。
>>> testResult = struct.unpack('<HH', testBytes)
>>> testResult
(256, 512)
ここで、< はエンディアンが little-endian であることを示します。したがって、\x00\x01 は 0*256+1 = 1 ではなく、00+1*256 = 256 になります。
>>> testResult = struct.unpack('<BBBB', testBytes)
>>> testResult
(0, 1, 0, 2)
B はデータが unsigned char であることを示し、1 バイトを占有します。したがって、\x00\x01\x00\x02 は 2 の unsigned short 値ではなく、4 の unsigned char 値に変換されます。
>>> testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
testResult = struct.unpack('<BBB', b'\x00\x01\x00\x02')
error: unpack requires a string argument of length 3
struct モジュールの公式ドキュメントをチェックして、フォーマット文字列 の詳細情報を取得できます。
Python 3 のバイト
bytes は Python 3 の組み込みデータ型であるため、bytes キーワードを使用して直接バイトを定義できます。
>>> testByte = bytes(18)
>>> type(testByte)
以下のように、バイトまたはバイト配列を直接定義することもできます。
>>> testBytes = b'\x01\x21\31\41'
>>> type(testBytes)
Python 3 でバイトを整数に変換する
Python 2.7 で既に導入されている struct モジュールに加えて、新しい Python 3 組み込み整数メソッドを使用して、バイトから整数への変換、つまり int.from_bytes() メソッドを実行することもできます。
int.from_bytes() 例
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big')
61712
この byteorder オプションは、struct.unpack() バイト順の定義のフォーマットに似ています。
int.from_bytes() は 3 番目の signed オプションがある、整数型を signed または unsigned に割り当てます。
>>> testBytes = b'\xF1\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
-3824
バイトが unsigned chart の場合に [] を使用する
データの形式が unsigned char である、1 バイトのみを含む場合は、オブジェクトインデックスを直接使用してアクセスし、データの整数を取得することもできます。
>>> testBytes = b'\xF1\x10'
>>> testBytes[0]
241
>>> testBytes[1]
16
