串行 Python3 上的二进制表示
Binary representation over serial Python3
我正在以 ascii 表示形式通过串行写入各种字节。
举个例子:bytes_to_write = '\aa' # Will write 01010101
现在我发送的一部分涉及计算需要传输的 4 个字节,我使用以下函数计算字节数:
def convert_addr_with_flag(addr, flag):
if(addr[0:1]!="0x"):
# String does not have hex start, for representation
addr = "0x" + addr
# Convert String to int
return binascii.unhexlify(str(hex(int(addr, 16) + (flag << 31))[2:].zfill(8))) # Return the int value, bit shiffted with flag
此函数将 return 二进制字符串而不是 ascii 字符串。这是一个例子...
convert_addr_with_flag("00ACFF21", 1) # Output: b'\x80\xac\xff!'
我的问题是如何将此输出转换为可以添加到数据包其他字节的形式。例如..
part_1 = '\xaa\xaa' # 2 bytes
part_2 = '\x55\x55' # 2 bytes
part_3 = convert_addr_with_flag("00ACFF21", 1) # 4 bytes
full_packet = part_1 + part_2 + part_3 # Will not work, as part_3 is a binary string (b'\x80\xac\xff!)
这是我已经尝试过的,
使用 decode("UTF-8)
和 UTF-16 和 ASCII。它无法理解字节串。
切片。使用 [2] 给我一个二进制字符,但不是 'second byte'
任何提示将不胜感激!
Python 3.4
decode
不工作,因为没有 part_3
的 ascii 表示; ascii 字符必须是 0 到 127(含)之间的整数。看起来这个例子中的 part_3
是 b'\x80\xac\xff!'
;前三个字节是 128、172 和 255,其中 none 是有效的 ascii。
如果您需要发送不在 0 到 127 之间的字节,您可能需要 part_1
和 part_2
作为字节字符串。
我正在以 ascii 表示形式通过串行写入各种字节。
举个例子:bytes_to_write = '\aa' # Will write 01010101
现在我发送的一部分涉及计算需要传输的 4 个字节,我使用以下函数计算字节数:
def convert_addr_with_flag(addr, flag):
if(addr[0:1]!="0x"):
# String does not have hex start, for representation
addr = "0x" + addr
# Convert String to int
return binascii.unhexlify(str(hex(int(addr, 16) + (flag << 31))[2:].zfill(8))) # Return the int value, bit shiffted with flag
此函数将 return 二进制字符串而不是 ascii 字符串。这是一个例子...
convert_addr_with_flag("00ACFF21", 1) # Output: b'\x80\xac\xff!'
我的问题是如何将此输出转换为可以添加到数据包其他字节的形式。例如..
part_1 = '\xaa\xaa' # 2 bytes
part_2 = '\x55\x55' # 2 bytes
part_3 = convert_addr_with_flag("00ACFF21", 1) # 4 bytes
full_packet = part_1 + part_2 + part_3 # Will not work, as part_3 is a binary string (b'\x80\xac\xff!)
这是我已经尝试过的,
使用 decode("UTF-8)
和 UTF-16 和 ASCII。它无法理解字节串。
切片。使用 [2] 给我一个二进制字符,但不是 'second byte'
任何提示将不胜感激!
Python 3.4
decode
不工作,因为没有 part_3
的 ascii 表示; ascii 字符必须是 0 到 127(含)之间的整数。看起来这个例子中的 part_3
是 b'\x80\xac\xff!'
;前三个字节是 128、172 和 255,其中 none 是有效的 ascii。
如果您需要发送不在 0 到 127 之间的字节,您可能需要 part_1
和 part_2
作为字节字符串。