.Convert String into a 2Bytearray(U32)- python

.Convert String into a 2Bytearray(U32)- python

我有一个字符串text="0000001011001100" 我想将这个字符串转换成一个 2 字节的数组,像这样 (b'\x00\x02')

byte_array=(socket.htons(text)).to_bytes(2,sys.byteorder)

但这不起作用并给出了 int 需要的错误 我已将文本转换为 int 但随后整个字符串发生变化

我需要这方面的帮助

您需要将二进制表示形式转换为 int 基数 2

text="0000001011001100"
num =int(text,2) #interprets string in base 2
result = chr(num) #is this what you want?

如果您正在使用 python 3.x 并希望通过拆分每 8 个字符将文本从任意长度的字符串转换为 bytes 对象:

bytes(int(text[i:i+8],2) for i in range(0,len(text),8))

但对于您的示例,它给出了 b'\x02\xcc',因此您可能想要不同的东西

您可以将文本转换为整数,然后您可以使用 struct 模块

import struct

text = "0000001011001100"
number = int(text, 2) # 716

result = struct.pack("h", number)

b'\xcc\x02'

# or with > to change bytes order

result = struct.pack(">h", number)

b'\x02\xcc'

参见:https://docs.python.org/3/library/struct.html