Re: NSStream, parsing NSData to struct
Re: NSStream, parsing NSData to struct
- Subject: Re: NSStream, parsing NSData to struct
- From: Graham Cox <email@hidden>
- Date: Thu, 9 Jul 2009 22:00:17 +1000
On 09/07/2009, at 8:28 PM, Carlo Gulliani wrote:
hello, i have NSData
...
NSData *d = [NSData dataWithBytes:(char*)&buffer length:len];
NSLog(@"%@", d); // <efbeadde 14000100 00000000 02100000 04000000
00000000 00000000 00000000 00185918 00000000 b08259d8 1e000000>
and I have structure
typedef struct mrim_header
{
u_long magic;
u_long proto;
u_long seq;
u_long msg;
u_long dlen;
u_longIP;
u_longPort;
u_charReserved[16];
}mrim_header;
how can i parse this data to this structure? In general, i should
catch some unsigned long variable, i guess it's 1e000000 and it must
be equal 30 so, before it i sent some packet and server returned to
me these bytes, now i should parse it
Please, let me know how to do it!
The simplest approach is this:
mrim_header* header = (mrim_header*)[d bytes];
(or cut out the middle man: mrim_header* header = (mrim_header*)buffer;)
!!!!!BUT!!!!!
This will only work reliably if the same compiler was used to to
generate the code handling both the receiver and transmitter of the
data stream, and the platforms at each end have the same byte ordering
and word lengths and so forth. Different compilers could pack the
structure slightly differently, or a field might be 32 bits at one end
and 64 at the other, or the platforms may have different padding
conventions. If there's any chance that you can't guarantee all of
this, you will need to be more careful and be certain about any
padding that could have been added to the stream at source. Also, you
*will* need to byte-swap each field if the byte ordering differs.
Since you mention a server it sounds like the data is coming across a
network. In that case I would be very careful about simply casting to
the header structure without being absolutely certain about the size
of the fields, and all the rest.
This general article is a good introduction to this: http://en.wikipedia.org/wiki/Data_structure_alignment
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden