我试图把一个矩阵从一个发射机串行地传送到接收机。为了做到这一点,我试图读取矩阵的每一行,将其转换成字节数组进行传输,然后在接收器中对其进行解码。到目前为止,当我将每一行转换为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]
从the documentation:
(
dtype
是data type
的缩写,是大量Numpy函数的参数。)除非您另外指定,
np.random.randint
将为您提供np.int
大小的值,这些值将占用四个字节的空间。(对于指定的随机范围,单字节是否足够并不重要。)要解决此问题,请指定appropriate数据类型:
看起来“a”是一个整数数组,其中每一个实际上都存储在4个字节中,因为整数可以保存比255大得多的值,255是无符号字节保存的最大值。因此,您关心的每个值之间的3个零的集合是“整数的其余部分”
我不记得np.random是否提供了将其初始化为字节数组的方法。或者您可以有一个中间步骤,在传输之前,将“行”中的每4个字节复制到一个新的字节数组“c”中
无论如何,希望这至少为你指明了正确的方向
相关问题 更多 >
编程相关推荐