使用python将bytearray转换为float
我正在使用python 2.7。只是想知道如何将bytearray转换为2字节浮点数。bytearray是:使用python将bytearray转换为float,python,bit-manipulation,bytearray,Python,Bit Manipulation,Bytearray,我正在使用python 2.7。只是想知道如何将bytearray转换为2字节浮点数。bytearray是: In[13]: temp Out[13]: `bytearray(b'\xd8[\xda[\xd8[\xda[\xd1[\xe1[\xeb[\xed[\xe7[\xeb[\xe7[\xea[\xd6[\xd5[\xd8[\xd5[\xd4[\xd3[\xe9[\xe2[\xe3[\xe5[\xe6[\xe8[\xdc[\xe6[\xe4[\xe4[\xe8[\xe2[\xd3[\xdb[
In[13]: temp
Out[13]: `bytearray(b'\xd8[\xda[\xd8[\xda[\xd1[\xe1[\xeb[\xed[\xe7[\xeb[\xe7[\xea[\xd6[\xd5[\xd8[\xd5[\xd4[\xd3[\xe9[\xe2[\xe3[\xe5[\xe6[\xe8[\xdc[\xe6[\xe4[\xe4[\xe8[\xe2[\xd3[\xdb[\xd1[\xda[\xda[\xd7[\xd1[\xd1[\xdf[\xd1[\xd4[\xdd[\xe6[\xdd[\xe3[\xe4[\xdf[\xe1[\xd0[\xd4[\xd7[\xd6[\xd7[\xd4[\xdf[\xdd[\xe0[\xe5[\xe0[\xdf[\xe0[\xdd[\xdd[\xe3[\xdc[\xde[\xd8[\xe0[\xde[\xdf[\xde[\xe2[\xe7[\xe2[\xe2[\xea[\xe1[\xe0[\xda[\xd4[\xd9[\xdb[\xd9[\xdd[\xe1[\xe3[\xe3[\xe2[\xe3[\xe7[\xe1[\xe5[\xe2[\xe8[\xe4[\xe3[')`
要转换为小尾端格式的96个浮点数,字节1为LSB,字节0为MSB 您可以使用
numpy
:
你说的是小尾端,但是你指定字节0是最重要的字节,也就是大尾端。你能提供一个更精确的解释吗?你的字节字符串是14字节长。在Python中,
float
的标准大小是4字节,而double
的标准大小是8字节。您的数据不适合整数浮点数
或双精度浮点数。确实需要16位精度浮点数吗??像这样?如果要将NumPy数组转换为标准Python标量列表,那么tolist
方法通常会更健壮、更高效。如果要将半精度浮点的NumPy数组转换为常规的双精度浮点数组,astype(float)
。
import numpy as np
# little-endian
x = np.fromstring(buffer(temp), dtype='<f2')
# big-endian
x = np.fromstring(buffer(temp), dtype='>f2')
# one value
float(x[0])
# all values
[float(a) for a in x]
# see user2357112 comments for other options