Deep discussion on method of judging a system whether a little endian or big endian

 let's directly looking at the code:

/* endian.c by vinco at 2011-09-07
* for testing the whether system is big endian or little endian
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int isLittleEndian(void)
{
	union
	{
		int a;
		char b;
	} endian;
	
	endian.a = 1;
	
	return (endian.b == 1);
}

int isLittleEndian_1(void)
{
	int num=0x00000001;//0x01
	unsigned  char ch=(unsigned char *)&num;
	
	return (ch == 1);
}

int main(int argc, char *argv[]) 
{  

	int i = 0;
	int num=0x00000001;
	unsigned  char *p=(unsigned char *)&num;

	for(i=0; i<sizeof(int)/sizeof(char); i++, p++)
	printf("%02x ", *p );

	putchar('\n');
	
#if 1
	if(isLittleEndian_1() == 1)
#else
	if(isLittleEndian() == 1)
#endif
		printf("The system is little endian\n");
	else
		printf("The system is big endian\n");
	return 0;

}

compile and run it  :

[vinco@IPPBX-Server ctest]$ make endian
cc     endian.c   -o endian
endian.c: In function isLittleEndian_1
endian.c:24: warning: initialization makes integer from pointer without a cast
[vinco@IPPBX-Server ctest]$ ./endian
01 00 00 00 
The system is big endian



as you see isLittleEndian() and isLittleEndian_1() are the typical way to test your system whether a little endian or big endian one, I believe that all of you make it clear at first  sight .

Howerver  I wonder that everybody really konw why  "isLittleEndian()"  is workable .

    if define "char ch", ch is initialized with 0 automatically,this is a only exception,
     (this case is ture at least in i386-Red Hat-gcc-4.1.2, Ubuntu -gcc-4.4.1, Fedora 10-gcc-4.3.2)
     because type of "int" , "char*" are not initialized with 0, NULL !!! , it doesn't that case.

 so it's not necessary ture if make it as below: ( note the order of union member ! )

 

  union
  {
   char b;
   int a;
  } endian;
 
  endian.b = 1;
  return (endian.a == 1);


 especially when the system you try to test is big endian, the member "endian.a" is uninitialized yet,
 the value of "endian.a" is uncertain, if it is 1, congratulations !!! the function return 0, means the
 system is a big endian one. However it's a small probability event, you take the wrong way at all

你可能感兴趣的:(Deep discussion on method of judging a system whether a little endian or big endian)