【发布时间】:2019-07-19 21:03:04
【问题描述】:
我正在开发一个通过蓝牙将传感器数据帧发送到主机的系统。主机运行一个处理传感器数据的 python 程序。传感器数据包含来自开发套件板上的 c 代码的 float(32) 值。这些值被分成 4 个字节(uint_8)。我想将这些值转换回 float32。我尝试了各种解决方案,但似乎都没有。有任何想法吗?
我尝试使用 struct.pack/struct.unpack 函数,但我要么误解了用法,要么有其他问题。 输入示例: [22, 132, 0, 0, 0, 0, 199, 230, 254, 255, 255....
def int2bytes(i):
hex_value = '{0:x}'.format(i)
# make length of hex_value a multiple of two
hex_value = '0' * (len(hex_value) % 2) + hex_value
return codecs.decode(hex_value, 'hex_codec')
def convert_from_byte(data):
byte_array = [0]*4
byte_count = 0
float_count = 0
data_size = len(data)
data_float = [] * 247
for i in range(data_size):
byte_array[byte_count] = int2bytes(data[i])
if(byte_count==3):
byte_array = ''.join(byte_array)
data_float[float_count] =struct.unpack('<f', byte_array)
float_count += 1
byte_count = 0
byte_count += 1
return data_float
我预计值在 0.005 左右,但可能会有很大差异。
【问题讨论】:
-
明确一点,[22,132,0,0] 是第一个浮点数,[0,0,199,230] 是第二个浮点数,等等?
-
struct.unpack('<f', bytes([22, 132, 0, 0]))怎么样?它不需要int2bytes,你可以使用data[:4]-struct.unpack('<f', bytes(data[:4]))- 然后得到data = data[4:]
标签: python python-2.7