清除bytearray上的拖尾\x00

2024-09-28 23:15:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把一个矩阵从一个发射机串行地传送到接收机。为了做到这一点,我试图读取矩阵的每一行,将其转换成字节数组进行传输,然后在接收器中对其进行解码。到目前为止,当我将每一行转换为bytearray时,每一个数字后面都有空元素

a = np.random.randint(0,255,size=(20,20))
print(a)


for row in a:
    b = bytearray(row)
    print(b)

假设从上一行开始的数组是[1,2,3,4]

预期成果: bytearray(b'\x01\x02\x03\x04')

但我得到的结果是: bytearray(b'\x01\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00...')

我的接收者使用list()对消息进行解码,使带有[1,2,3,4]的数组对接收者变成[1,0,0,0,0,0,3,0,0,0,0,4,0,0,0,0]


Tags: 字节矩阵数字数组解码rowprint接收器
2条回答

the documentation

dtype : dtype, optional

Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’.

New in version 1.11.0.

dtypedata type的缩写,是大量Numpy函数的参数。)

除非您另外指定,np.random.randint将为您提供np.int大小的值,这些值将占用四个字节的空间。(对于指定的随机范围,单字节是否足够并不重要。)

要解决此问题,请指定appropriate数据类型:

a = np.random.randint(0, 255, size=(20,20), dtype=np.uint8)

看起来“a”是一个整数数组,其中每一个实际上都存储在4个字节中,因为整数可以保存比255大得多的值,255是无符号字节保存的最大值。因此,您关心的每个值之间的3个零的集合是“整数的其余部分”

我不记得np.random是否提供了将其初始化为字节数组的方法。或者您可以有一个中间步骤,在传输之前,将“行”中的每4个字节复制到一个新的字节数组“c”中

无论如何,希望这至少为你指明了正确的方向

相关问题 更多 >