Chinaunix首页 | 论坛 | 博客
  • 博客访问: 974445
  • 博文数量: 238
  • 博客积分: 2842
  • 博客等级: 少校
  • 技术积分: 2765
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-16 00:20
个人简介

stdlf

文章分类

全部博文(238)

文章存档

2013年(6)

2012年(13)

2011年(82)

2010年(89)

2009年(48)

我的朋友

分类:

2010-02-15 23:25:41

一、概念及详解

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

先回顾两个关键词,MSB和LSB:

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

大端模式(big-edian)

big-endian:MSB存放在最低端的地址上。

举例,双字节数0x1234以big-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-endian:LSB存放在最低端的地址上。

举例,双字节数0x1234以little-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*/

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