bg***@yahoo.com writes:
I have an array as follows -
char arr[100];
Now I wish to copy the following int -
int tmp = 0x01020304;
into this array, at element[12].
This following would have the same result -
ThePacket3[12] = 1;
ThePacket3[13] = 2;
ThePacket3[14] = 3;
ThePacket3[15] = 4;
How can I do this without breaking up my int into 4 bytes and assigning
each element one by one?
int isn't necessarily 4 bytes, bytes aren't necessarily 8 bits, and
the value 0x01020304 isn't necessarily stored in the order 1, 2, 3, 4;
it's commonly 4, 3, 2, 1, but it could theoretically be in any of the
24 possible orders.
If you want to break the value of tmp down into 4 8-bit quantities,
and store then in successive elements of your array (it it called
"arr" or "ThePacket3"?), the only portable way to do it is by copying
each byte individually, after extracting them using shifts and masks.
If you're willing to make non-portable assumptions about how an int is
represented, you can use memcpy(), but your code will break when
ported to a system with different byte ordering.
If you're trying to guarantee network byte ordering, there are
functions that will handle this for you ("ntohl" and friends), but
they're not part of standard C. If your system has them, searching
your documentation for "ntohl" should be enough to get you started.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.