【问题标题】:Float Array to Byte Array and Vise Versa浮点数组到字节数组,反之亦然
【发布时间】:2019-02-14 07:21:32
【问题描述】:

我的最终目标是能够通过 UDP 套接字发送一组浮点数,但现在我只是想让一些东西在 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 套接字将浮点数据从客户端(一个接一个)发送到服务器。我的最终目标是使用数组来执行此操作,以便我可以使用 matplotlib 绘制值。

【问题讨论】:

    标签: arrays python-3.x sockets udp byte


    【解决方案1】:

    你在这里只装了一个浮点数。但是随后您尝试将结果缓冲区的第一个字节(已隐式转换为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)
    

    【讨论】:

      猜你喜欢
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 2011-07-02
      • 2015-02-16
      • 2014-01-09
      • 1970-01-01
      • 2010-12-27
      相关资源
      最近更新 更多