簡體   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