Reputation: 310
I am working on parsing a binary data file containing a very well defined header (this many bytes for this data type, followed by this many bytes for this other data type). It goes like this
0-2: 3 chars
3 : 1 unsigned short
4-6: 24-bit unsigned integer
...
The part that is alien to me is doing this in Matlab. In an ideal world, I would like to read this header straight into a struct, then parsing the binary data that follows, then parse the next header.
Is there an I/O function that will be able to read into a properly aligned and sized struct, as one could do in C? I presume this is not the case, and I will need to write a function that reads each morsel of the header and pieces it together into a struct.
Examples of parsing of file or network protocol headers would be good links to share. Thanks!
Upvotes: 0
Views: 653
Reputation: 36710
Ratbert baisically got it in his comments, a matlab struct has nothing to do with a c struct. There is no way to directly map fields of a matlab struct to memory like it is done in matlab. The simple answer is no.
The usual way is to create the struct in m, for 99% of the cases this is the right choice. Further in Matlab all structs are arrays, so you may put all your packets in to one struct, indexing them for example with:
packets(3).from_ip % Ip of the third packet
packets(9).payload(23:49) %bytes 23 to 49 of packet 9
Just to give you an idea how a well thought data structure in Matlab could look like.
There is the remaining 1% of cases, which are especially formats difficult to unpack in matlab or some very performance critical cases. In these cases you may write a mex function, which is basically a C(++) function which can be called like a matlab function. But keep in mind that mex-functions can not return c-structs. You must repack your data into the corresponding matlab data type. There is no automatism to do this.
Upvotes: 2