void endianTest_union()
{
union // sizeof(int) == 4
{
int i;
unsigned char ch[4];
} U;
U.i = 0x12345678; // writing to int i
if(U.ch[0]==0x78 && U.ch[1]==0x56
&& U.ch[2]==0x34 && U.ch[3]==0x12) // followed by
puts("Little Endian"); //reading from unsigned char: OK
else if (U.ch[3]==0x78 && U.ch[2]==0x56
&& U.ch[1]==0x34 && U.ch[0]==0x12)
puts("Big Endian");
else
puts("Middle Endian");
}
void endianTest_sans_union()
{
int n = 0x12345678; // sizeof(int) == 4
unsigned char* p = (unsigned char*)&n; // reinterpreting int
// through unsigned char ptr: OK
if(p[0]==0x78 && p[1]==0x56
&& p[2]==0x34 && p[3]==0x12)
puts("Little Endian");
else if (p[3]==0x78 && p[2]==0x56
&& p[1]==0x34 && p[0]==0x12)
puts("Big Endian");
else
puts("Middle Endian");
}
void undef_beh()
{
int n = 0x12345678; // sizeof(int) == 4
short int * p = (short int *)&n; // reinterpreting int
// through short int ptr: not OK
printf("\nlower short int: %x\n",p[0]); // breaks strict aliasing rule
printf("higher short int: %x\n",p[1]); // fortunately this produces warning (in gcc)
// still prints p[0] == 0x5678; p[1] == 0x1234
}
void undef_beh_union()
{
union // sizeof(int) == 4
{
int i;
short int p[2];
} U;
U.i = 0x12345678; // writing to int i
printf("\nlower short int: %x\n",U.p[0]); // followed by
printf("higher short int: %x\n",U.p[1]); // reading from short int member : not OK
// prints U.p[0] == 0x5678; U.p[1] == 0x1234
}
int main()
{
endianTest_union();
endianTest_sans_union();
undef_beh();
undef_beh_union();
return 0;
}