私は16進値の長い文字列を持っていますが、これはすべて次のようになります。
'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
実際の文字列は、波形の1024フレームです。これらの16進値を、次のような整数値のリストに変換したいと思います。
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]
これらの16進値をintに変換するにはどうすればよいですか?
私は16進値の長い文字列を持っていますが、これはすべて次のようになります。
'\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
実際の文字列は、波形の1024フレームです。これらの16進値を、次のような整数値のリストに変換したいと思います。
[0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0]
これらの16進値をintに変換するにはどうすればよいですか?
>>> import struct
>>> s = '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
>>> struct.unpack('11B',s)
(0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0)
これにより、のtuple
代わりになりlist
ますが、必要に応じて変換できると思います。
In [11]: a
Out[11]: '\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00'
In [12]: import array
In [13]: array.array('B', a)
Out[13]: array('B', [0, 0, 0, 1, 0, 0, 0, 255, 255, 0, 0])
いくつかのタイミング。
$ python -m timeit -s 'text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00";' ' map(ord, text)'
1000000 loops, best of 3: 0.775 usec per loop
$ python -m timeit -s 'import array;text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00"' 'array.array("B", text)'
1000000 loops, best of 3: 0.29 usec per loop
$ python -m timeit -s 'import struct; text = "\x00\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00"' 'struct.unpack("11B",text)'
10000000 loops, best of 3: 0.165 usec per loop