Little Endian String을 정수로 변환하십시오
문제
웨이브 모듈을 사용하여 웨이브 파일에서 샘플을 읽었지만 샘플을 문자열로 제공합니다. \x00
).
이것을 파이썬 정수 또는 numpy.int16 유형으로 변환하는 가장 쉬운 방법은 무엇입니까? (결국 Numpy.int16이 될 것이므로 직접 가면 괜찮습니다).
코드는 Little Endian 및 Big Endian 프로세서에서 작업해야합니다.
해결책
그만큼 struct
모듈은 포장 된 데이터를 Python 값으로 변환하고 그 반대도 마찬가지입니다.
>>> import struct
>>> struct.unpack("<h", "\x00\x05")
(1280,)
>>> struct.unpack("<h", "\x00\x06")
(1536,)
>>> struct.unpack("<h", "\x01\x06")
(1537,)
"H"는 짧은 INT 또는 16 비트 int를 의미합니다. "<"는 리틀 엔디언을 사용하는 것을 의미합니다.
다른 팁
struct
하나 또는 적은 수의 2 바이트 문자열을 정수로 변환해야한다면 괜찮습니다. array
그리고 numpy
그 자체가 더 나은 옵션입니다. 구체적으로, Numpy.FromString (적절한 사람과 호출 dtype
인수)은 문자열에서 바이트를 배열로 직접 변환 할 수 있습니다 ( dtype
이다). (만약에 numpy.little_endian
거짓이면 바이트를 교환해야합니다. 여기 더 많은 토론을하려면 기본적으로 byteswap
방금 구축 한 배열 개체의 메소드 fromstring
).
케빈 버크의 대답 이 질문에 이진 문자열이 단일 짧은 정수를 나타내는 경우에도 잘 작동하지만 문자열이 여러 정수를 나타내는 이진 데이터를 보유하면 문자열이 나타내는 각 추가 정수에 대해 추가 'H'를 추가해야합니다.
파이썬 2의 경우
대표하는 작은 엔디언 문자열을 변환합니다 2 정수
import struct
iValues = struct.unpack("<hh", "\x00\x04\x01\x05")
print(iValues)
출력 : (1024, 1281)
대표하는 작은 엔디언 문자열을 변환합니다 3 정수
import struct
iValues = struct.unpack("<hhh", "\x00\x04\x01\x05\x03\x04")
print(iValues)
출력 : (1024, 1281, 1027)
분명히, "H"문자가 얼마나 필요한지 항상 추측하는 것은 현실적이지 않습니다.
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)
출력 : (1024, 1281, 1027)
파이썬 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)
출력 : (1024, 1281, 1027)