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

huangapple go评论49阅读模式
英文:

convert byte string to double precission

问题

以下是翻译好的内容:

我正在使用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个字节转换为b'\x3F\xFE\xD8\x55\x80\x00\x00\x00'。我尝试过将消息中的8个字节数据转换为列表,但是我得到的是一个字符串列表,不知道如何处理它。

提前感谢您的帮助。

英文:

I am using the CAN interface with an Arduino Shield and Python3 on my host. I get the following message via serial interface of Arduino:

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

The 8 byte data is in double precission 1.9278159141540527.
For conversion I use the following python code:

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

My problem is, that I don't know how to convert the 8 bytes of the message string. I don't know how to get from this: 3F FE D8 55 80 00 00 00 to this b'\x3F\xFE\xD8\x55\x80\x00\x00\x00'

I tried to make list of the 8 bytes data in the message, but than I have a list of strings and don't know how to deal with it.

Thanks in advance

答案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
英文:

You can create a bytearray from your input string:

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

Output:

1.9278159141540527

huangapple
  • 本文由 发表于 2023年7月31日 19:56:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803369.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定