Last active
August 29, 2015 14:26
-
-
Save TurplePurtle/5a7cb84eae512056c644 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
// serializing macros | |
#define serialize1(name, t1) void name(char* buffer, t1 a) { \ | |
memcpy(buffer, &a, sizeof(t1)); } | |
#define serialize2(name, t1,t2) void name(char* buffer, t1 a, t2 b) { \ | |
memcpy(buffer, &a, sizeof(t1)); \ | |
memcpy(buffer + sizeof(t1), &b, sizeof(t1)); } | |
serialize1(foo, int); // define serializer foo(int) | |
serialize2(bar, char, int); // define serializer bar(char, int) | |
int main(void) { | |
char buffer[255] = {0}; // serialize bytes into this buffer | |
foo(buffer, 97); // serialize (int) 97 into buffer | |
bar(buffer + sizeof(int), 'b', 99); // serialize (char)'b' and (int)99 into buffer | |
// print buffer (in hex) to check it | |
int length = sizeof(int) + sizeof(char) + sizeof(int); | |
for (int i=0; i<length; i++) printf("%p ", buffer[i]); | |
printf("\n"); | |
// output: | |
// 0x61 0x0 0x0 0x0 0x62 0x63 0x0 0x0 0x0 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment