简体   繁体   English

如何解码 python 中的 HEX 和 ASCII 数据?

[英]How to decode HEX and ASCII data in python?

import serial
from time import sleep

t = serial.Serial(
    "/dev/serial0", 19200, parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITES_ONE, timeout=0.5
)
cw = [0x01, 0x03, 0x00, 0x00, 0x03, 0x05, 0xCB]
t.write(serial.to_bytes(cw))
rx = t.read()
sleep(0.03)
data = t.inWaiting()
rx += t.read(rx)
print(rx)

This is the code I'm using and the output for rx is b'\x01\x03\x06\x00\x07\x01,\x00\x00T\x80' .这是我正在使用的代码, rx的 output 是b'\x01\x03\x06\x00\x07\x01,\x00\x00T\x80'

And the format of decoding it is 01 03 06 + voltage higher byte + voltage lower byte + current higher byte + current lower byte + status high + low + crc + parity.解码格式为 01 03 06 + 电压高字节 + 电压低字节 + 电流高字节 + 电流低字节 + 状态高 + 低 + crc + 奇偶校验。

How can I decode the voltage and current?如何解码电压和电流? I think it is in hex and ascii format.我认为它是十六进制和ASCII格式。

There are a couple of ways to do this depending on the context this is being used in. There is the Python struct library and there is the from_bytes int class method.根据使用的上下文,有几种方法可以做到这一点。有 Python结构库和from_bytes int class 方法。

The data is in little endian format because the higher byte is before the lower byte.数据采用小端格式,因为高字节在低字节之前。 I am also assuming that these values can be signed.我还假设这些值可以签名。

Examples of how to do this:如何执行此操作的示例:

>>> rx = b'\x01\x03\x06\x00\x07\x01,\x00\x00T\x80'
>>> import struct
>>> voltage, current = struct.unpack('<3xhh4x', rx)
>>> print(voltage)
1792
>>> print(current)
11265
>>> voltage2 = int.from_bytes(rx[3:5], 'little', signed=True)
>>> current2 = int.from_bytes(rx[5:7], 'little', signed=True)
>>> print(voltage2)
1792
>>> print(current2)
11265

Looking at the values it might be that the values need to have the decimal point moved by a couple of places if you were expecting approximately 18 volts.查看这些值,如果您期望大约 18 伏,这些值可能需要将小数点移动几位。 eg例如

>>> voltage * 10**-2
17.92

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM