Can somebody please tell me how go about copying the elements of a structure into a byte array. Your assistance is greatly appreciated.
Thanks in advance!
Can somebody please tell me how go about copying the elements of a structure into a byte array. Your assistance is greatly appreciated.
Thanks in advance!
Do you care about copying the padding bytes which may be between members of the structure or not?
Further, if you intend to send this array of bytes to some external machine, do you care about fixing things like the endian-ness of data types?
Does your structure contain pointers, and do you want to intelligently do the "right thing" with the data which is being pointed to?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I do not want the padding bytes.
I'm not worried about endian-ness.
There are no pointers in the structure.
I'm mainly just looking for a C syntax example.
One way would be to memcpy member by member.
Code:#include <stdio.h> #include <string.h> struct dumb { char broiled; short circuit; long johns; double entendre; }; size_t serialize(unsigned char *dst, const struct dumb *object) { size_t i = 0; memcpy(&dst[i], &object->broiled, sizeof object->broiled); i += sizeof object->broiled; memcpy(&dst[i], &object->circuit, sizeof object->circuit); i += sizeof object->circuit; memcpy(&dst[i], &object->johns, sizeof object->johns); i += sizeof object->johns; memcpy(&dst[i], &object->entendre, sizeof object->entendre); i += sizeof object->entendre; return i; } void showbytes(const void *object, size_t size) { const unsigned char *byte; for ( byte = object; size--; ++byte ) { printf("%02X", *byte); } putchar('\n'); } int main() { int member; struct dumb by[sizeof member] = { { 'A', 0x1234, 0x12345678, 123.456}, }; unsigned char buffer [ sizeof by[0] ]; showbytes(buffer, serialize(buffer, by)); return 0; } /* my output 4134127856341277BE9F1A2FDD5E40 */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Thanks Dave!