判断机器的大小端问题
思路:联合体union的存放顺序是所有成员都从低地址开始存放,利用该特性就可以轻松地获得了
CPU对内存采用Little-endian还是Big-endian模式读写。
1 int checkCPU( ) 2 { 3 { 4 union w 5 { 6 int a; 7 char b; 8 } c; 9 c.a = 1; 10 return(c.b ==1); 11 } 12 }
另一种思路:
int i = 0x00000001; if(*(char*)&i) puts("little"); else puts("big);
在linux内核中实现的方法:
static union { charc[4]; unsigned long l; }endian_test = {{'l','?','?','b'}}; #define ENDIANNESS((char)endian_test.l)
ENDIANNESS='l'标识系统为little endian,为'b'表示big endian