#include<stdio.h>
static union
{
char c[4];
unsigned long l;
}endian_test = { {'l','?','?','b'} };
#define ENDIANNESS ( (char)endian_test.l )
union U{
char s[9]; //size: 9
int n; //size: 4
double d; //size: 8
}; //size: 16
union 的最小的size是所包含的所有类型的基本长度的最小公倍数才行。
struct S
{
char s[9]; //size: 9
int n; //size: 4
double d; //size: 8
}; //size: 24
int main()
{
printf( "sizeof int = [%ld]
", sizeof( int ) );
printf( "sizeof unsigned long = [%ld]
", sizeof(unsigned long ) );
printf( "sizeof double = [%ld]
", sizeof( double ) );
printf( "sizeof union U = [%ld]
", sizeof( union U ) );
printf( "sizeof struct S = [%ld]
", sizeof( struct S ) );
printf( "ENDIANESS = %c
", ENDIANNESS );
}

Detect endianness at run-time
1 #include <stdint.h>
2
3 enum {
4 ENDIAN_UNKNOWN,
5 ENDIAN_BIG,
6 ENDIAN_LITTLE,
7 ENDIAN_BIG_WORD, /* Middle-endian, Honeywell 316 style */
8 ENDIAN_LITTLE_WORD /* Middle-endian, PDP-11 style */
9 };
10
11 int endianness(void)
12 {
13 union
14 {
15 uint32_t value;
16 uint8_t data[sizeof(uint32_t)];
17 } number;
18
19 number.data[0] = 0x00;
20 number.data[1] = 0x01;
21 number.data[2] = 0x02;
22 number.data[3] = 0x03;
23
24 switch (number.value)
25 {
26 case UINT32_C(0x00010203): return ENDIAN_BIG;
27 case UINT32_C(0x03020100): return ENDIAN_LITTLE;
28 case UINT32_C(0x02030001): return ENDIAN_BIG_WORD;
29 case UINT32_C(0x01000302): return ENDIAN_LITTLE_WORD;
30 default: return ENDIAN_UNKNOWN;
31 }
32 }