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;
}
As a program?
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_twith auint8_t[4], I can check to see which byte comes first. See: http://en.wikipedia.org/wiki/Big_endianGCC 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.htmlSee 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
printfwill print “1633837924”, since a big-endian machine will interpret the'a'character as the most significant byte in the int.The second
printfwill just print “abcd”, since the value ofuhas been copied byte-by-byte back and forth fromi.