Converso pouco corda endian para inteiro
Pergunta
Eu li amostras fora de um arquivo de onda utilizando o módulo de onda, mas dá as amostras como uma string, que está fora de onda por isso é pouco endian (por exemplo, \x00
).
O que é a maneira mais fácil de converter isso em um inteiro python, ou um tipo numpy.int16? (Ele acabará por se tornar um numpy.int16, assim que ir diretamente para lá é bom).
Código precisa trabalhar em little endian e grandes processadores endian.
Solução
Os convertidos módulo struct
embalado dados para valores Python, e vice-versa.
>>> import struct
>>> struct.unpack("<h", "\x00\x05")
(1280,)
>>> struct.unpack("<h", "\x00\x06")
(1536,)
>>> struct.unpack("<h", "\x01\x06")
(1537,)
"h" significa um curto int, ou de 16 bits int. "<" Significa usar little-endian.
Outras dicas
struct
é bom se você tem que converter um ou um pequeno número de 2 strings de bytes para inteiros, mas array
e numpy
si são melhores opções. Especificamente, numpy.fromstring (chamado com o dtype
apropriada argumento) pode diretamente converter os bytes de sua seqüência a uma série de (o que quer que dtype
é). (Se numpy.little_endian
é falso, então você vai ter que trocar os bytes - veja aqui para mais discussão, mas basicamente você vai querer chamar o método byteswap
no objeto matriz que você acabou de construir com fromstring
).
Para Python 2
Converter Little Endian String que representa 2 inteiros
import struct
iValues = struct.unpack("<hh", "\x00\x04\x01\x05")
print(iValues)
Output: (1024, 1281)
Converter Little Endian String que representa 3 inteiros
import struct
iValues = struct.unpack("<hhh", "\x00\x04\x01\x05\x03\x04")
print(iValues)
Output: (1024, 1281, 1027)
Obviamente, não é realista para sempre adivinhar quantas "h" caracteres são necessários, assim:
import struct
# A string that holds some unknown quantity of integers in binary form
strBinary_Values = "\x00\x04\x01\x05\x03\x04"
# Calculate the number of integers that are represented by binary string data
iQty_of_Values = len(strBinary_Values)/2
# Produce the string of required "h" values
h = "h" * int(iQty_of_Values)
iValues = struct.unpack("<"+h, strBinary_Values)
print(iValues)
Output: (1024, 1281, 1027)
Para Python 3
import struct
# A string that holds some unknown quantity of integers in binary form
strBinary_Values = "\x00\x04\x01\x05\x03\x04"
# Calculate the number of integers that are represented by binary string data
iQty_of_Values = len(strBinary_Values)/2
# Produce the string of required "h" values
h = "h" * int(iQty_of_Values)
iValues = struct.unpack("<"+h, bytes(strBinary_Values, "utf8"))
print(iValues)
Output: (1024, 1281, 1027)