damafeng11的个人空间 https://www.eechina.com/space-uid-4205.html [收藏] [复制] [RSS]

博客

Big-endian AND Little-endian

已有 1193 次阅读2009-10-28 15:14

Endianism,端序,是指用来存储数据的方法,它定义了数据类型对字节进行寻址的方式。

两种端序方式:
1、Little-endian,小端序,是将低位字节存储在内存偏移地址较低的地址中,将高位字节存储在内存偏移地址较高的地址中;
2、Big-endian,大端序,则是将低位字节存储在内存偏移地址较高的地址中,将高位字节存储在内存偏移地址较低的地址中。

比如:
0x12345678 在 big-endian 系统上的布局
内存偏移量       0          1           2           3 
内存内容       0x12     0x34     0x56     0x78 

0x12345678 在 little-endian 系统上的布局
内存偏移量       0           1          2           3 
内存内容       0x78     0x56     0x34     0x12

机器大小端和环境相关,可以使用下面的办法判断机器的大小端:
  1. #include <cstdlib>
  2. #include <iostream>

  3. using namespace std;

  4. union test
  5. {
  6.     int i;
  7.     char c;
  8. };
  9.     
  10. int main()
  11. {
  12.     union test t;
  13.     t.i = 0x12345678;
  14.     if(t.c == 0x78)
  15.         cout<<"Little-endism"<<endl;
  16.     else
  17.     cout<<"Big-endism"<<endl;
  18.     system("pause");
  19.     return 0;    
  20. }
复制代码
在获悉环境的大小端后,就可以进行细致的分析了,
比如 Little-endlism 环境下:
  1. #include <cstdlib>
  2. #include <iostream>

  3. using namespace std;

  4. union test
  5. {
  6.     int i;
  7.     char c;
  8. };
  9.     
  10. int main()
  11. {
  12.     union test t;
  13.     t.i = 0x12345678;
  14.     short int x= *((short int *)(&(t.c)));
  15.     cout<<hex<<x;
  16.     system("pause");
  17.     return 0;    
  18. }
复制代码
0x12345678 在 little-endian 系统上的布局
内存偏移量     0           1          2           3 
内存内容     0x78     0x56     0x34     0x12

short int 为2字节(32位平台下)
将访问:
内存偏移量     0          1 
内存内容     0x78     0x56 
所以, 最后的结果为 (0x)5678


Endianism 在以下情况中非常重要:
1.使用位掩码时
2.对象的间接指针地址部分

合理使用联合体、位域等手段,可以在一定程度避免端序问题。

路过

鸡蛋

鲜花

握手

雷人

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 立即注册

关于我们  -  服务条款  -  使用指南  -  站点地图  -  友情链接  -  联系我们
电子工程网 © 版权所有   京ICP备16069177号 | 京公网安备11010502021702
返回顶部