1

My ultimate goal is to be able to send an array of floats over a UDP socket, but for now I'm just trying to get a few things working in python3. The code below works just fine:

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

Output:

 b'\xeax\xac@'
(5.3897600173950195,)

But when I try this I get:

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])

Output:

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'

How can I turn a float array to byte array and vise versa. The reason I'm tryin to accomplish this is because the first code allows me to send float data from a client to server (one by one) using a UDP socket. My ultimate goal is to do this with an array so I can plot the values using matplotlib.

1 Answer 1

2

You're only packing a single float here. But then you're trying to pass the first byte of the resulting buffer (which was implicitly converted to int) to unpack. You need to give it the entire buffer. Also, to do this in a more general way, you want to first encode the number of items in your array as an integer.

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)

(The *electrode_data means to flatten the list: it's the same as electrode_data[0], electrode_data[1]...)

If you really only want to do one at a time:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.