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 *)#
return (ch == 1);
}
int main(int argc, char *argv[])
{
int i = 0;
int num=0x00000001;
unsigned char *p=(unsigned char *)#
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

本文深入探讨了LittleEndian函数如何通过利用指针和类型转换,判断当前系统的端序是大端序还是小端序,并解释了其背后的原理。包括通过实例演示函数的工作方式以及为什么在特定情况下它可以正确地识别系统的端序。
1013

被折叠的 条评论
为什么被折叠?



