arrays - float 组到字节数组,反之亦然

标签 arrays python-3.x sockets udp byte

我的最终目标是能够通过UDP套接字发送一个float数组,但是现在我只是想让python3中的一些东西工作。
下面的代码可以正常工作:

import struct
fake_data = struct.pack('f', 5.38976) 
print(fake_data) 
data1 = struct.unpack('f', fake_data) 
print(data1)

输出:
 b'\xeax\xac@'
(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套接字将 float 数据从客户端发送到服务器(一个到一个)。我的最终目标是使用数组执行此操作,以便可以使用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)

关于arrays - float 组到字节数组,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52247938/

相关文章:

javascript - 将货币紧凑表示法(例如 '$1.5k' )转换为整数(例如 1500)

Python 字符串 "b"前缀(字节文字)

python-3.x - 如何设置云运行应用程序以在 python 中接收发布/订阅消息?

java - 客户端-服务器架构中的容错

.net - ListenUriMode.Unique如何为客户工作?

ruby - 。包括?在 Ruby 中不起作用的 if 语句中

arrays - Mongodb如何处理大数组字段?

java - 与目标虚拟机断开连接

macos - Python - Mechanize - 导入失败(MacOS 10.7 上的 python 3.3)

python - 函数 round() 没有像我预期的那样工作