Chinaunix首页 | 论坛 | 博客
  • 博客访问: 509593
  • 博文数量: 91
  • 博客积分: 9223
  • 博客等级: 中将
  • 技术积分: 1777
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-02 17:37
个人简介

!!!!!!!!!!!!

文章分类

全部博文(91)

文章存档

2013年(3)

2012年(4)

2011年(37)

2010年(36)

2009年(9)

2008年(2)

分类: LINUX

2010-07-19 09:38:30

解析大端模式和小端模式

 

作者:王正伟,讲师。

一、概念及详解

在各种体系的计算机中通常采用的字节存储机制主要有两种: big-endianlittle-endian,即大端模式和小端模式。

先回顾两个关键词,MSBLSB

MSB:Most Significant Bit ------- 最高有效位
        LSB:Least Significant Bit -------
最低有效位

大端模式(big-edian

big-endianMSB存放在最低端的地址上。

举例,双字节数0x1234big-endian的方式存在起始地址0x00002000中:

| data |<-- address
        | 0x12 |<-- 0x00002000
        | 0x34 |<-- 0x00002001

Big-Endian中,对于bit序列中的序号编排方式如下(以双字节数0x8B8A为例):

bit | 0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15
------MSB----------------------------------LSB
val | 1 0 0 0 1 0 1 1 | 1 0 0 0 1 0 1 0 |
    +--------------------------------------------+
    = 0x8 B 8 A

小端模式(little-endian)

little-endianLSB存放在最低端的地址上。

举例,双字节数0x1234little-endian的方式存在起始地址0x00002000中:

| data |<-- address
        | 0x34 |<-- 0x00002000
        | 0x12 |<-- 0x00002001

Little-Endian中,对于bit序列中的序号编排和Big-Endian刚好相反,其方式如下(以双字节数0x8B8A为例):

bit | 15 14 13 12 11 10 9 8 | 7 6 5 4 3 2 1 0
------MSB-----------------------------------LSB
val | 1 0 0 0 1 0 1 1 | 1 0 0 0 1 0 1 0 |
+---------------------------------------------+
= 0x8 B 8 A

二、数组在大端小端情况下的存储:

unsigned int value = 0x12345678为例,分别看看在两种字节序下其存储情况,我们可以用unsigned char buf[4]来表示value
Big-Endian:
低地址存放高位,如下:

高地址
        ---------------
        buf[3] (0x78) --
低位
        buf[2] (0x56)
        buf[1] (0x34)
        buf[0] (0x12) --
高位
        ---------------
        
低地址

Little-Endian: 低地址存放低位,如下:

高地址
        ---------------
        buf[3] (0x12) --
高位
        buf[2] (0x34)
        buf[1] (0x56)
        buf[0] (0x78) --
低位
        --------------
        
低地址

三、大端小端转换方法:

Big-Endian转换成Little-Endian如下:

#define BigtoLittle16(A)              ((((uint16)(A) & 0xff00) >> 8) | \
                                       (((uint16)(A) & 0x00ff) << 8))
#define BigtoLittle32(A)         ((((uint32)(A) & 0xff000000) >> 24) | \
                                (((uint32)(A) & 0x00ff0000) >> 8) | \
                                 (((uint32)(A) & 0x0000ff00) << 8) | \
                                  (((uint32)(A) & 0x000000ff) << 24))

四、大端小端检测方法:

如何检查处理器是big-endian还是little-endian?

联合体union的存放顺序是所有成员都从低地址开始存放,利用该特性就可以轻松地获得了CPU对内存采用Little-endian还是Big-endian模式读写。

int checkCPUendian()
        {
                union
                {
                        unsigned int a;
                        unsigned char b;
                }c;
                c.a = 1;
                return (c.b == 1);
        }
        /*return 1 : little-endian, return 0:big-endian*/

阅读(700) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~