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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值