Chinaunix首页 | 论坛 | 博客
  • 博客访问: 583696
  • 博文数量: 109
  • 博客积分: 1463
  • 博客等级: 上尉
  • 技术积分: 859
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-22 13:21
个人简介

希望和广大热爱技术的童鞋一起交流,成长。

文章分类

全部博文(109)

文章存档

2017年(1)

2016年(2)

2015年(18)

2014年(1)

2013年(9)

2012年(15)

2011年(63)

分类: C/C++

2011-09-19 20:46:15

一、概念及详解

  在各种体系的计算机中通常采用的字节存储机制主要有两种: 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) |
  1.              (((uint32)(A) & 0x00ff0000) >> 8) | \
  2.         (((uint32)(A) & 0x0000ff00) << 8) | \
  3.                (((uint32)(A) & 0x000000ff) << 24))
 四、大端小端检测方法:

  如何检查是big-endian还是little-endian?

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

  1. int checkCPUendian()
  2.         {
  3.                 union
  4.                 {
  5.                      unsigned int a;
  6.                      unsigned char b;
  7.                 }c;
  8.                 c.a = 1;
  9.                 return (c.b == 1);
  10.         }
  11. /*return 1 : little-endian, return 0:big-endian*/
阅读(640) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~