第一種方法,使用強制類型轉換的方式。C 語言在把佔用2個字節的 short 變量強制轉換爲 char 之後,會把 short 變量的首地址賦給 char 變量,可以根據 char 變量的值判斷系統字節序是 大端 還是 小端。
第二種方法,利用 聯合類型 的特性。聯合類型 共享同一段內存,首地址是相同的。
測試環境:
ubuntu 10.04 amd 64.
/*******en/*******************
* 文件名:endian.c
******************/
#include <stdio.h>
* 使用類型的強制轉換實現little-endian與big-endian的判斷
*********************************************************
* 返回值:
* 1 表示是小端字節序。
* 0 表示不是小端字節序。
*********************************************************/
int is_little_endian_a(void)
{
unsigned short flag = 0x4321;
if(*(unsigned char*)&flag == 0x21)
return 1;
else
return 0;
}
* 利用聯合的特點來判斷little-endian與big-endian
*********************************************************************************
* 返回值:
* 1 表示是小端字節序。
* 0 表示是大端字節序。
* -1 表示不能使用這種方法確定字節序。比如有的機器的 short 長度不是 2 。
********************************************************************************/
int is_little_endian_b(void)
{
union endian_un{
short var;
char bits[sizeof(short)];
};
flag.var=0x0102;
if(sizeof(short) == 2){
if(flag.bits[0] == 1 && flag.bits[1] == 2)
return 0;
else if(flag.bits[0] == 2 && flag.bits[1] == 1)
return 1;
else
return -1;
}
return -1;
}
{
int type = 0;
if (1 == type)
printf("judged by first method, little-endian\n");
else if (0 == type)
printf("judged by first method, big-endian\n");
if (1 == type)
printf("judged by second method, little-endian\n");
else if (0 == type)
printf("judged by second method, big-endian\n");
else
printf("can't judge it\n");
}