判断字节序的C函数
时间:2010-10-19 来源:Bean_lee
1
程序员面试宝典上有 这个题目,但是比较生涩,面试宝典就是这个德行,这个函数摘自UNIX网络编程,比较好懂。同时祝贺我的博客开张大吉
#include<stdio.h> 2 #include<stdlib.h> 3 4 5 int main() 6 { 7 union{ 8 short s; 9 char c[sizeof(short)]; 10 }UN; 11 UN.s = 0x0102; 12 13 14 if(UN.c[0]==1 &&UN.c[1] == 2) 15 printf("big-endian\n"); 16 else if(UN.c[0] == 2 && UN.c[1] == 1) 17 printf("little-endian\n"); 18 else 19 printf("Unknown\n"); 20 21 }
另外一种比较直接的方法是 1 #include<stdio.h> 2 #include<stdlib.h> 3 4 5 6 int main() 7 { 8 #if __BYTE_ORDER == __LITTLE_ENDIAN 9 printf("little endian \n"); 10 #endif 11 12 #if __BYTE_ORDER == __BIG_ENDIAN 13 printf("big endian\n"); 14 #endif 15 16 return 0; 17 }
22
#include<stdio.h> 2 #include<stdlib.h> 3 4 5 int main() 6 { 7 union{ 8 short s; 9 char c[sizeof(short)]; 10 }UN; 11 UN.s = 0x0102; 12 13 14 if(UN.c[0]==1 &&UN.c[1] == 2) 15 printf("big-endian\n"); 16 else if(UN.c[0] == 2 && UN.c[1] == 1) 17 printf("little-endian\n"); 18 else 19 printf("Unknown\n"); 20 21 }
另外一种比较直接的方法是 1 #include<stdio.h> 2 #include<stdlib.h> 3 4 5 6 int main() 7 { 8 #if __BYTE_ORDER == __LITTLE_ENDIAN 9 printf("little endian \n"); 10 #endif 11 12 #if __BYTE_ORDER == __BIG_ENDIAN 13 printf("big endian\n"); 14 #endif 15 16 return 0; 17 }
22
相关阅读 更多 +