关于不同的字节存储顺序 Little endian 和 Big endian,如果有不清楚的地方请查阅维基百科:http://en.wikipedia.org/wiki/Endianness
C code如下:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
union TestEndian_Unit
{
uint16_t value;
uint8_t bytes[2];
};
/*!
This function get endianness of current running environment.
Return value: 0 -- Little endian
1 -- Big endian
Exception 0xFF00 means error occurs.
Reference: http://en.wikipedia.org/wiki/Endianness
For example: x86, x86-64 and Windows on PowerPC use little endian;
FreeBSD on PowerPC and SPARC use big endian.
*/
int IsBigEndian()
{
union TestEndian_Unit flag;
flag.value = 0xFF00;
if(flag.bytes[0] == 0x00 && flag.bytes[1] == 0xFF)
{
return 0;
}
else if(flag.bytes[0] == 0xFF && flag.bytes[1] == 0x00)
{
return 1;
}
else
{
fprintf(stderr, "Error occurs in function IsBigEndian().\n");
exit(0xFF00);
}
}
如果函数返回0,表示当前系统是Little endian;如果返回1,表示当前系统是Big endian。
参考文献:
- Endianness http://en.wikipedia.org/wiki/Endianness
- Big and Little Endian http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html