給出系統大小端識別的代碼,僅供參考。
傳統寫法:
int get_order()
{
union endian
{
short s;
char c[2];
} order;
order.s = 0x1234;
if (order.c[0] == 0x12 && order.c[1] == 0x34)
{
return 1; /* big endian */
}
else
{
return 0; /* little endian */
}
}
簡單寫法:
int get_order()
{
short s = 1;
short *ps = &s
char *pc;
pc = (char *)ps;
if (*pc == 0)
{
return 1; /* big endian */
}
else
{
return 0; /* little endian */
}
}
參數寫法:
static int test_order(char *c)
{
*c = 1;
return 0;
}
int get_order()
{
int i = 0;
test_order(&i);
if (i == 0)
{
return 1; /* big endian */
}
else
{
return 0; /* little endian */
}
}
偷懶寫法:
int get_order()
{
if (htons(1) == 1)
{
return 1; /* big endian */
}
else
{
return 0; /* little endian */
}
}
作者:aile770339804