如何将 Python 中的 ASCII "Bytes" 列表转换为十六进制字节
How do I convert a list of ASCII "Bytes" in Python into Hex Bytes
我有一个 ASCII 列表 "bytes",我需要将其转换为十六进制,然后通过串行端口发送。
例如,取下面的列表:
list_to_send=['FE','FE','98','E0''07', 'D2', '00','FD"]
我想将每个字节转换为十六进制,例如第一个字节如下所示:
b'\xfe'
我尝试过使用 binascii,但我认为我的用法不正确。
谢谢!
如果您使用的是 Python 3.5 及更高版本,请使用此
b'\xFE'.hex()
如果你想使用 binascii,那么:
import binascii
binascii.hexlify('FE'.encode('utf8'))
还有很多其他方法...
了解更多信息
http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
使用 join()
str="b'"
for x in list_to_send:
str=str+"\x"+x
str=str+"'"
Sending hex over serial with python
我有一个 ASCII 列表 "bytes",我需要将其转换为十六进制,然后通过串行端口发送。
例如,取下面的列表:
list_to_send=['FE','FE','98','E0''07', 'D2', '00','FD"]
我想将每个字节转换为十六进制,例如第一个字节如下所示:
b'\xfe'
我尝试过使用 binascii,但我认为我的用法不正确。
谢谢!
如果您使用的是 Python 3.5 及更高版本,请使用此
b'\xFE'.hex()
如果你想使用 binascii,那么:
import binascii
binascii.hexlify('FE'.encode('utf8'))
还有很多其他方法... 了解更多信息 http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
使用 join()
str="b'"
for x in list_to_send:
str=str+"\x"+x
str=str+"'"
Sending hex over serial with python