Skip to content

Instantly share code, notes, and snippets.

@lotherk
Created April 10, 2017 10:42
Show Gist options
  • Save lotherk/210a740303dd5666ee85f734c7de6f7d to your computer and use it in GitHub Desktop.
Save lotherk/210a740303dd5666ee85f734c7de6f7d to your computer and use it in GitHub Desktop.
Struct to Bytes and Bytes to Struct
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int pack(void *strct, unsigned char buf[], size_t size) {
int i = 0;
unsigned char *byte;
for (byte = (unsigned char *)strct; size--; ++byte)
buf[i++] = *byte;
return 0;
}
#define unpack(strct, buf, size) \
memcpy(strct, buf, size);
struct test {
long foo;
long bar;
};
int main() {
struct test t = { 5L, 6L };
unsigned char bytes[sizeof(t)];
pack(&t, bytes, sizeof(t));
struct test f;
unpack(&f, bytes, sizeof(f));
printf("foo: %lu, bar: %lu\n", f.foo, f.bar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment