union判断CPU是little-endian还是big-endian存储

 

利用联合体的特殊存储方式,便能检测出来cpu所使用的事big-endian或者是little-endian的存储方式。

1.判断系统是Big liden 或者是little  ledin

方法1:
int check()
{     union check
       {
              int i;
              char ch;
       }c;
       c.i  =1;
       return (c.ch == 1);
}返回值为==1的时候为小端,不等于1的时候为大端联合体中 变量i 和ch共用同一地址空间,它们都是从低地址开始存放。变量i的值为0x00 00 00 01, 如果是小端模式则01在低地址上,ch的值如果为01则是小端模式,否则是大端模式。

//在C语言参考手册的第六章.1.2节中提供了一个移植性更好的测试程序:

#include <stdio.h>

int main( )

{

       union w

       {  

              int a;

              char b[sizeof(int)]; 

       } c;

       c.a = 1;

       if(c.b[0] == 1)

              printf("the addressing is little-endian\n");

       else if(c.b[sizeof(int)-1] == 1)

              printf("the addressing is big-endian\n");

       return 0;

}

posted @ 2013-07-07 14:48  瀚海一漂一九九一  阅读(438)  评论(0)    收藏  举报