Last active
August 29, 2015 14:20
-
-
Save latsku/bbe9d4d93ca0822fbe6b to your computer and use it in GitHub Desktop.
Test file to demonstrate structure packing on C
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
/** | |
* \file | |
* Test to show how packed structures work in C. | |
* | |
* Eric S. Raymond has written a great introduction to structure packing | |
* (http://www.catb.org/esr/structure-packing/) | |
* | |
* @author: Lari Lehtomäki <[email protected]> | |
* @date: 2015-05-29 | |
* | |
*/ | |
#include <stdio.h> | |
/** | |
* Test structure | |
* Try with and without the packed attribute. | |
*/ | |
struct myStruct { | |
//struct __attribute__ ((__packed__)) myStruct { | |
short unsigned int a; | |
unsigned int b; | |
short unsigned int c; | |
}; | |
/** Buffer where the structs points. */ | |
static char buffer[20]; | |
/** | |
* On little-endian machine (x86) the output with packed structure | |
* should be something like: | |
* \code | |
* | |
* sym: 8 | |
* sym.a: 2 | |
* sym.k: 4 | |
* sym.m: 2 | |
* *si = (myStruct) { | |
* .a = 0x0123, | |
* .b = 0x456789ab, | |
* .c = 0xcdef | |
* }; | |
* 0x601041: 0x23 0x01 0xab 0x89 0x67 0x45 0xef 0xcd | |
* | |
* \endcode | |
*/ | |
int main(int argc, const char *argv) { | |
struct myStruct *si = (struct myStruct *)buffer; | |
*si = (struct myStruct) { | |
.a = 0x0123, | |
.b = 0x456789ab, | |
.c = 0xcdef | |
}; | |
printf("sym: %lu\n", sizeof(*si)); | |
printf("sym.a: %lu\n", sizeof(si->a)); | |
printf("sym.k: %lu\n", sizeof(si->b)); | |
printf("sym.m: %lu\n", sizeof(si->c)); | |
/* Printing of struct */ | |
printf(" *si = (struct myStruct) {\n"); | |
printf(" .a = %#06x,\n", si->a); | |
printf(" .b = %#06x,\n", si->b); | |
printf(" .c = %#06x \n", si->c); | |
printf(" };\n"); | |
/* Printing of memory */ | |
void * p = &si; | |
int i = 0; | |
printf("%p: ", &(buffer[i])+1); | |
for (i = 0; i < sizeof(*si); i++ ) { | |
printf("%#04hhx ", (char)buffer[i]); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment