将字节字符串转换为双精度

问题描述 投票:0回答:1

我在主机上使用带有 Arduino Shield 和 Python3 的 CAN 接口。我通过 Arduino 的串行接口收到以下消息:

b'0006.381 RX: [00000004](00) 3F FE D8 55 80 00 00 00 \r\n'

8字节数据为双精度1.9278159141540527。 为了进行转换,我使用以下 python 代码:

struct.unpack('>d', b'\x3F\xFE\xD8\x55\x80\x00\x00\x00')[0]

我的问题是,我不知道如何转换消息字符串的 8 个字节。我不知道如何从这个:

3F FE D8 55 80 00 00 00
到这个
b'\x3F\xFE\xD8\x55\x80\x00\x00\x00'

我尝试列出消息中的 8 字节数据,但我有一个字符串列表,不知道如何处理它。

提前致谢

python-3.x can-bus
1个回答
2
投票

您可以从输入字符串创建一个

bytearray

import struct
s = "3F FE D8 55 80 00 00 00"
ba = bytearray.fromhex(s)
r = struct.unpack('>d', ba)[0]

输出:

1.9278159141540527
© www.soinside.com 2019 - 2024. All rights reserved.