判断大端小端机器的两种方法

作者在 2011-09-03 10:52:21 发布以下内容
第一种,使用位段:
#include <stdio.h>

struct data
{
    unsigned int a:3;
    unsigned int b:2;
    unsigned int c:3;
};

int main()
{
    struct data abc;
    unsigned char* s = (unsigned char*) &abc;
    *s = 0x99;
    if(abc.a == 1)
        printf("you are using big_endian machine\n");
    else
        printf("you are using little_endian machine\n");
}
 第2种方法:
union data
{
    struct t {
        char a;
        char b;
    } d;
    short c;
};

int main()
{
    union data x;
    x.c = 0x0102;
    if(sizeof(short) == 2)
    {
        if(x.d.a == 1 && x.d.b == 2)
            printf("your machine is big-endian\n");
        else
            if(x.d.a == 2 && x.d.b == 1)
                printf("your machine is little-endian\n");
            else
                printf("unknown\n");
    }
    else
        printf("sizeof(short) = %d\n", sizeof(short));
    return 0;
}
 
系统 | 阅读 1197 次
文章评论,共2条
hbjoylee
2011-09-01 16:34
1
第一种方法的输出反了。
hbjoylee
2011-09-01 16:36
2
int checkCPU( )<br />
{<br />
&nbsp; &nbsp; &nbsp; &nbsp; //联合体union的存放顺序是所有成员都从低地址开始存放。<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; union w<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int&nbsp;&nbsp;a;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char b;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } c;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.a = 1;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return(c.b ==1);//真时为小端&nbsp; &nbsp; &nbsp; &nbsp; <br />
}
游客请输入验证码
浏览25435次