经典笔试题:用C写一个函数测试当前机器大小端模式


“用C语言写一个函数测试当前机器的大小端模式”是一个经典的笔试题,如下使用两种方式进行解答:

1. 用union来测试机器的大小端

 1 #include <stdio.h>
 2 
 3 union test  4 {  5     int a;  6     char b;  7 };  8 
 9 int endian_test(void) 10 { 11  union test t1; 12     t1.a = 1; 13     return t1.b; 14 } 15 
16 int main(void) 17 { 18     int i = endian_test(); 19     if(i == 1) 20  { 21         printf("is little endian.\n");
23  } 24     else
25  { 26         printf("is big endian.\n");
28  } 29     
30     printf("i = %d.\n", i); 31     
32     return 0; 33 }

2. 用指针测试机器大小端

1 #include <stdio.h>
2 
3 int main() 4 { 5   int a = 1; 6   char b = *((char *)&a); 7 
8   return 0; 9 }

注: 通信系统中,通信双方数据传送方式中,先发低字节的方式叫小端,先发高字节的方式叫大端。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM