I want to create something like structure in C but in Python. Specifically I want to sth like that:
typedef struct __attribute__((__packed__))
{
float x[4];
uint8 y;
int z;
} structName;
in Python. I read somewhere that I can use named tuple but want to avoid padding and I don't know how to do it in Python. Can anyone show me how to do that? I will use it in UDP communication.
If you want to serialize (ex:save into file or send trough network) then, you should check out struct library basically you can define how to save your data, how many bytes and which order.
You can use a class in python to represent your struct and add two function for pack it into smaller binary data and unpack it from it if you need it again
Your example should be:
import struct
class StructName():
def __init__(self, xs=None, y=None, z=None):
self.xs = xs
self.y = y
self.z = z
def pack(self):
return struct.pack("!4fBi", *self.xs, self.y, self.z)
def unpack(self, packed_bytes):
*self.xs, self.y, self.z = struct.unpack("!4fBi", packed_bytes)
if __name__ == "__main__":
s = StructName([1.0, 0.5, 2.0, 0.], 255, 42)
tmp = StructName()
bytedata = s.pack()
print("s", s.xs, s.y, s.z) # s [1.0, 0.5, 2.0, 0.0] 255 42
print(len(bytedata), bytedata) # 21 b'\x00\x00\x80?\x00\x00\x00?\x00\x00\x00@\x00\x00\x00\x00\xff\x00\x00\x00*\x00\x00\x00'
tmp.unpack(bytedata) # fill data into tmp class
tmp.xs[0] = 42.5
print("tmp", tmp.xs, tmp.y, tmp.z) # tmp [42.5, 0.5, 2.0, 0.0] 255 42
The format string in the pack and unpack function is "!4fBi" where:
For more check out this section: Format Characters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With