Union u{Short
A;
char c;
};
u u;
In the book C programming Language is described in this way:
1) A consortium is a structure;
2 The offset of all its members relative to the base address is 0;
3 This structure space to be large enough to accommodate the most "wide" members;
4 its alignment should be suitable for all the members;
So a federation in memory stored in the form of the following figure:
From the diagram, it's easy to see that the address of variable A, C, and U is 0x20000000
u.a=0x1234;
The small-end mode (the high byte of the data is stored in a high memory address) is stored as follows:
In big-endian mode (the high byte of the data is kept in the low memory address), the storage is as follows:
So, as long as we take out the value of variable C, to compare, if its value is 34h, then the machine is a small-end mode, if its value is 12h, then the machine is big-endian mode.
The implementation code is as follows:
#include <stdio.h>
Union u{
int A;
char c;
} u;
int main ()
{
u.a=0x1234;
if (0x34 = = u.c)
{
printf ("The Machine is little-end.\n");
}
else if (0x12 = = u.c)
{
printf ("The Machine is big-end.\n");
}
return 0;
}