如何解码特殊字符串和转换十六进制4字节

问题描述

我从设备收到了有效的字符串并且在解码之前(out_1 = b'\ x00 \ x03 \ x02 \ x01 ** \ x90 ** \ x00 ** \ x14Q ** \ xc2 \ x80〜\ x00 \ x80 \ xe2 ** \ x7f @ ** \ n)。

但是我不知道如何安排打印4个字节(十六进制),即out_1并发现\ x90无法解码。我该怎么办?我的代码在下面:

import sys
import serial

com1_1 = serial.Serial(port='COM8',baudrate=115200,bytesize=8,stopbits=1,timeout=2,parity='N')

get1 = com1_1.readline()
print("out_1=," get1)
out2= get1.decode('utf-8') %Did't run and error
print('out_2=',out2)

out_1=b'\x00\x03\x02\x01\x90\x00\x14Q\xc2\x80~\x00\x80\xe2\x7f@\n
out_2 = 0000 0003 0002 0001 (I want the result)

非常感谢您。

解决方法

您可以使用以下方法将您的 out_1 转换为 out_2 格式

out_1 = b'\x00\x03\x02\x01\x90\x00\x14Q\xc2\x80~\x00\x80\xe2\x7f@\n'
out_2 = ' '.join(str(d).zfill(4) for d in out_1)
print(out_2)

输出:

0000 0003 0002 0001 0144 0000 0020 0081 0194 0128 0126 0000 0128 0226 0127 0064 0010