I have a bytes buffer called data and need to read its content. It was created by a C++ program and sent over the network. Its layout is known, but a has a variable length. Here is an example:
print(data)
id = int.from_bytes(data[:4], byteorder='little')
w = int.from_bytes(data[4:8], byteorder='little')
h = int.from_bytes(data[8:12], byteorder='little')
a = np.frombuffer(data[12:], dtype='f4')
print(id, w, h, a)
Is there a more elegant way of extracting its content without specifying exact positions of each variable, e.g. data[8:12], but specifying their order and individual size instead? Any other way this kind of task is usually done?
The struct syntax only allows for fixed amounts of data. But you can mix and match:
a, b, c = struct.unpack('<3i', data)
arr = np.frombuffer(data[12:], dtype='f4')
If you need a NumPy array as the result for the variable-length data, then you’ll have to use a NumPy-provided unpacker (or else an array constructor) anyway.