/* This is a short program to illustrate endianness. This performs a simple memory trick that allows us to view the actual order of bytes in memory. it then prints out what the program perceives as the byte order and the actual order in memory. To compile: gcc -o endian 08-endian.c To run: ./endian C. Andrews 2013-09-20 */ #include #include int main(int argc, char * argv[]){ // the union stores both of these items in the same location in memory // So, if I access this using .i, I can treat this memory as an int, and if // I use C, it is an array of characters. union { uint32_t i; char c[sizeof(uint32_t)]; } u; // Set the value using the integer u.i = 0x12345678; // test the first byte in the array to see if it has the "high" byte if (u.c[0] == 0x12){ printf("Big Endian\n"); }else{ printf("Little Endian\n"); } // print out what the program sees // we are using bit twiddling to mask out and extract the actual bytes printf("Apparent storage: "); for (int i = 3; i >=0; i--){ printf("%hhx ", (u.i >> (i * 8)) & 0xff); } printf( "\n"); // print out how it is stored in memory // this just reads the data out of the array printf("Actual storage: "); for (int i = 0; i < 4; i++){ printf("%hhx ", u.c[i]); } printf( "\n"); return 0; }