Test big endian
c, endianness, gcc
Solution
As a program?
#include <stdio.h>
#include <stdint.h>
int main(int argc, char** argv) {
union {
uint32_t word;
uint8_t bytes[4];
} test_struct;
test_struct.word = 0x1;
if (test_struct.bytes[0] != 0)
printf("little-endian\n");
else
printf("big-endian\n");
return 0;
}
On a little-endian architecture, the least significant byte is stored first. On a big-endian architecture, the most-significant byte is stored first. So by overlaying a `uint32_t` with a `uint8_t[4]`, I can check to see which byte comes first. See: http://en.wikipedia.org/wiki/Big_endian
GCC in particular defines the `__BYTE_ORDER__` macro as an extension. You can test against `__ORDER_BIG_ENDIAN__`, `__ORDER_LITTLE_ENDIAN__`, and `__ORDER_PDP_ENDIAN__` (which I didn't know existed!) -- see http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
See also http://en.wikipedia.org/wiki/Big_endian
As for running code in an endianness that doesn't match your machine's native endianness, then you're going to have to compile and run it on an architecture that has that different endianness. So you are going to need to cross-compile, and run on an emulator or virtual machine.
edit: ah, I didn't see the first `printf()`.
The first `printf` will print "1633837924", since a big-endian machine will interpret the `'a'` character as the most significant byte in the int.
The second `printf` will just print "abcd", since the value of `u` has been copied byte-by-byte back and forth from `i`.
Problem
Possible Duplicate: Little vs Big Endianess: How to interpret the test Is there an easy method to test code with gcc or any online compiler like ideone for big endian? I don't want to use qemu or virtual machines EDIT Can someone explain the behavior of this piece of code on a system using big endian? ``` #include <stdio.h> #include <string.h> #include <stdint.h> int main (void) { int32_t i; unsigned char u[4] = {'a', 'b', 'c', 'd'}; memcpy(&i, u, sizeof(u)); printf("%d\n", i); memcpy(u, &i, sizeof(i)); for (i = 0; i < 4; i++) { printf("%c", u[i]); } printf("\n"); return 0; } ```