c - Order of data while casting array to struct -
say have following struct:
typedef struct mystruct { unsigned short a; /* 16 bit unsigned integer*/ unsigned short b; /* 16 bit unsigned integer*/ unsigned long c; /* 32 bit unsigned integer*/ }my_struct;
and data array (the content demonstration):
unsigned short data[] = {0x0011, 0x1100, 0x0001, 0x0fff };
then perform folliwing:
my_struct *ms; ms = (my_struct *) data; printf("a is: %x\n",(*ms).a); printf("b is: %x\n",(*ms).b); printf("c is: %x\n",(*ms).c);
i expect data read sequentially ms, "left right", in case output be:
a is: 11 b is: 1100 c is: 10fff
however happens is:
a is: 11 b is: 1100 c is: fff0001
why happen? behavior should expect when casting arrays structs way?
what behavior should expect when casting arrays structs way?
the answer is, depends. welcome wonderful world of endian-ness: http://en.wikipedia.org/wiki/endianness
the gist is, assuming data stored in manner in expect human read. big endian. you're on x86 machine, however, little endian. means significant digits @ end of 4 bytes, not @ start. that's why 2nd half short showing before first half of short.
you different results on different architectures method.
Comments
Post a Comment