C语言大小端判断程序
大端模式
所谓的大端模式,是指数据的高位,保存在内存的低地址中,而数据的低位,保存在内存的高地址中,这样的存储模式有点儿类似于把数据当作字符串顺序处理:地址由小向大增加,而数据从高位往低位放;
例子:
0000430: e684 6c4e 0100 1800 53ef 0100 0100 0000
0000440: b484 6c4e 004e ed00 0000 0000 0100 0000
在大端模式下,前16位应该这样读: e684
记忆方法: 地址的增长顺序与值的增长顺序相反
小端模式
所谓的小端模式,是指数据的高位保存在内存的高地址中,而数 据的低位保存在内存的低地址中,这种存储模式将地址的高低和数据位权有效地结合起来,高地址部分权值高,低地址部分权值低,和我们的逻辑方法一致。
例子:
0000430: e684 6c4e 0100 1800 53ef 0100 0100 0000
0000440: b484 6c4e 004e ed00 0000 0000 0100 0000
在小端模式下,前16位应该这样读: 84e6
记忆方法: 地址的增长顺序与值的增长顺序相同
版本一:
/*
File name : Endian.c
Version : 0.0.1
Author : LiMing
Date : 2012-02-25,19:14,Saturday
Descriptioin: Test whether the user's compute architecture is big-endian or little-endian
Test environment: Dev-C++ 5.1.0.0
Test result:
The x0 = 0x22
The x1 = 0x11
shows that the x86 architechture is little-endian
*/
#include <stdio.h>
union data
{
int inter;
char ch;
};
int main(void)
{
union data c;
c.inter = 1;
if(c.ch == 1)
printf("The compute is little-endian.\n");
else
printf("The compute is big-endian,\n");
getchar();
return 0;
}
版本二:
/*
0x3839
little endian
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union AA
{
int i;
char a[2];
};
int is_little_endian()
{
union check
{
int i;
char ch;
}c;
c.i = 1;
return (c.ch == 1);
}
int main()
{
int ret;
union AA *p, u;
p = &u;
memset(&u, 0, sizeof(union AA));
p->a[0] = 0x39;
p->a[1] = 0x38;
printf("0x%x\n", p->i);
if(is_little_endian())
{
printf("little endian!\n");
}
else
{
printf("big endian!\n");
}
getchar();
return 0;
}
版本三:
/*
File name : endian02.c
Version : 0.0.1
Author : LiMing
Date : 2012-02-26,10:40,Sunday
Descriptioin: Use keyword 'union' to test whether the user's compute architecture is big-endian or little-endian
Test environment: Dev-C++ 5.1.0.0
Test result:
The compute is little-endian.
*/
#include <stdio.h>
int main(void)
{
short int x;
char x0,x1;
x = 0x1122;
x0 = ((char *)&x)[0];
x1 = ((char *)&x)[1];
printf("The x0 = 0x%x\n",x0);
printf("The x1 = 0x%x\n",x1);
getchar();
return 0;
}
版本四:
/*
File name : Endian01.c
Version : 0.0.2
Author : LiMing
Date : 2012-02-25,19:14,Saturday
Descriptioin: Use keyword 'union' to test whether the user's compute architecture is big-endian or little-endian
Test environment: Dev-C++ 5.1.0.0
Test result:
The compute is little-endian.
*/
#include <stdio.h>
#include <stdlib.h>
union data
{
short inter;
char ch;
};
int main(void)
{
union data c;
c.inter = 0x1122;
if(c.ch == 0x22)
printf("The compute is little-endian.\n");
else
printf("The compute is big-endian,\n");
getchar();
return 0;
}