我的最终目标是能够通过UDP套接字发送浮点数组,但现在我只是想让一些东西在python3中工作。 下面的代码工作得很好:
import struct
fake_data = struct.pack('f', 5.38976)
print(fake_data)
data1 = struct.unpack('f', fake_data)
print(data1)
输出:
b'xeaxxac@'
(5.3897600173950195,)
但是当我尝试这个时,我得到:
electrode_data = [1.22, -2.33, 3.44]
for i in range(3):
data = struct.pack('!d', electrode_data[i]) # float -> bytes
print(data[i])
x = struct.unpack('!d', data[i]) # bytes -> float
print(x[i])
输出:
63
Traceback (most recent call last):
File "cbutton.py", line 18, in <module>
x = struct.unpack('!d', data[i]) # bytes -> float
TypeError: a bytes-like object is required, not 'int'
如何将浮点数组转换为字节数组,反之亦然。我尝试完成此操作的原因是,第一个代码允许我使用 UDP 套接字将浮点数据从客户端发送到服务器(一个接一个(。我的最终目标是使用数组来做到这一点,这样我就可以使用 matplotlib 绘制值。
你在这里只打包了一个浮子。但是,您尝试将生成的缓冲区的第一个字节(已隐式转换为int
(传递给unpack
。您需要为其提供整个缓冲区。此外,若要以更通用的方式执行此操作,需要首先将数组中的项数编码为整数。
import struct
electrode_data = [1.22, -2.33, 3.44]
# First encode the number of data items, then the actual items
data = struct.pack("!I" + "d" * len(electrode_data), len(electrode_data), *electrode_data)
print(data)
# Pull the number of encoded items (Note a tuple is returned!)
elen = struct.unpack_from("!I", data)[0]
# Now pull the array of items
e2 = struct.unpack_from("!" + "d" * elen, data, 4)
print(e2)
(*electrode_data
的意思是扁平化列表:它与electrode_data[0], electrode_data[1]...
相同(
如果你真的只想一次做一个:
for elem in electrode_data:
data = struct.pack("!d", elem)
print(data)
# Again note that unpack *always* returns a tuple (even if only one member)
d2 = struct.unpack("!d", data)[0]
print(d2)