数据存储大小端

大小端模式介绍

  • 大端(存储)模式:是指一个数据的低位字节序的内容放在高地址处,高位字节序存的内容放在低地址处。
  • 小端(存储)模式:是指一个数据的低位字节序内容存放在低地址处,高位字节序的内容存放在高地址处。(可以总结为“小小小”即低位、低地址、小端)

MSB:MoST Significant Bit :最高有效位。
LSB:Least Significant Bit :最低有效位。

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 

大端小端检测方法

#include <stdio.h>


int main()
{

    unsigned short x = 0x1234;
    char x0,x1;

    x0 = ((char*)&x)[0]; 
    printf("low address of x0 is%x:\n",&x0);
    x1 = ((char*)&x)[1];
    printf("high address of x1 is%x:\n",&x1);

    printf("x0=0x%x\nx1=0x%x\n",x0,x1);//if output is x0=0x12,x1=0x34,it's big end,else it's little end
    return 0;

}
posted @ 2019-03-24 11:16  youngliu91  阅读(1128)  评论(0编辑  收藏  举报