大端 小端 C

来源:互联网 发布:通讯软件下载 编辑:程序博客网 时间:2024/05/18 02:38

所谓的大端模式,是指数据的低位保存在内存的高地址中,而数据的高位,保存在内存的低地址中;

所谓的小端模式,是指数据的低位保存在内存的低地址中,而数据的高位保存在内存的高地址中。

 

#include <iostream>

using namespace std;
union
{
int i;
char x[2];
}a;

int main()
{
       a.x[0] = 10;
       a.x[1] = 1;
       printf("%d\n",a.i); 
       printf("%xd\n",a.i);
       system("pause");
       return 0;
}  //dev_c++  运行结果 0X010a  所以是小端!

short int x;

char x0,x1;

x=0x1122;

x0=((char*)&x)[0];  //低地址单元
x1=((char*)&x)[1];  //高地址单元

若x0=0x11,则是大端; 若x0=0x22(数据的低位存在低地址中),则是小端......

 

 

再来个例子:

main()
{
union{ /*定义一个联合*/
int i;
struct{ /*在联合中定义一个结构*/
char first;
char second;
}half;
}number;
number.i=0x4241; /*联合成员赋值*/
printf("%c%c/n", number.half.first, mumber.half.second);
number.half.first='a'; /*联合中结构成员赋值*/
number.half.second='b';
printf("%x/n", number.i);
getch();
}
答案: AB (0x41对应'A',是低位;Ox42对应'B',是高位)

              6261   //a ,b的ask码

 

原创粉丝点击