作者在 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种方法: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");
}
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;
}
{
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;
}