繁体   English   中英

将字符串转换为十六进制并通过 Python 中的串行发送

[英]Convert String to hex and send via serial in Python

我想将字符串400AM49L01转换为十六进制形式(然后转换为字节) b'x\34\x30\x30\x41\x4d\x34\x39\x4c\x30' ,所以我可以用pySerial编写它。 我已经尝试将包含单个十六进制(如0x31 (等于4 ))的列表元素转换为字节,但这将导致b'400AM49L01'

device = '400AM49L01'
device = device.encode()
device = bytes(device)
device = str(binascii.hexlify(device), 'ascii')
code = '0x'
text = []
count = 0
for i in device:
    if count % 2 == 0 and count != 0:
        text.append(code)
        code = '0x'
        count = 0
    code += i
    count += 1
text.append((code))
result = bytes([int(x, 0) for x in text])

真心期待您的帮助!

以下代码将给出您期望的结果。

my_str = '400AM49L01'

"".join(hex(ord(c)) for c in my_str).encode()

# Output
# '0x340x300x300x410x4d0x340x390x4c0x300x31'

它在做什么?

  1. 为了将字符串转换为十六进制,您需要使用ord()将每个字符转换为 ascii 表中的 integer 值。
  2. 使用 function hex()将每个 int 值转换为十六进制。
  3. 连接使用join()生成的所有十六进制值。
  4. 使用.encode()将 str 编码为字节。

问候!

暂无
暂无

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

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