Created
April 10, 2017 10:42
-
-
Save lotherk/210a740303dd5666ee85f734c7de6f7d to your computer and use it in GitHub Desktop.
Struct to Bytes and Bytes to Struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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