概念:
大小端模式是指各种体系的计算机系统(CPU的体系架构:PPC、ARM、MIPS等)中采用的字节存储机制(多字节数据类型),分为:大端模式和小端模式两种。
大端模式:是指数据的高字节保存在内存的低地址中,数据的低字节保存在内存的高地址中。
小端模式:是指数据的高字节保存在内存的高地址中,数据的低字节保存在内存的低地址中。
主机序:不同的CPU有不同的字节序类型,这些字节序是指整数在内存中的保存顺序,这个叫主机序。
网络序:是TCP/IP中规定好的一种数据表示格式,它与具体的CPU类型、操作系统等无关,从而可以保证数据在不同主机之间传输时能被正确 的解释,网络序采用大端模式
大小端模式下数据在内存中的存储情况:
以数据 0x12345678 为例:
大端模式下数据在内存中的分布为:
地址 | 0 | 1 | 2 | 3 |
数据 | 0x12 | 0x34 | 0x56 | 0x78 |
数据的高字节保存在内存的低地址中,数据的低字节保存在内存的高地址中
小端模式下数据在内存中的分布为:
地址 | 0 | 1 | 2 | 3 |
数据 | 0x78 | 0x56 | 0x34 | 0x12 |
一个小端系统的验证例子:
// BigOrLittle.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include "typedef.h" int _tmain(int argc, _TCHAR* argv[]) { UINT32 uiValue = 0x12345678; UCHAR aucBuffer[4] = {0}; aucBuffer[0] = ((UCHAR*)&uiValue)[0]; aucBuffer[1] = ((UCHAR*)&uiValue)[1]; aucBuffer[2] = ((UCHAR*)&uiValue)[2]; aucBuffer[3] = ((UCHAR*)&uiValue)[3]; printf("Little endian data: %x %x %x %x",aucBuffer[0], aucBuffer[1], aucBuffer[2], aucBuffer[3]); getchar(); return 0; }
大小端的检测方法:
下面这段代码可以用来测试你的编译器是大端模式还是小端模式:
大小端的转换方法:// BigOrLittle.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include "typedef.h" typedef union tagBigOrLittleData { UINT32 uiA; UCHAR ucB; UCHAR ucC; UCHAR ucD; UCHAR ucE; }BigOrLittleData_U; UINT32 CheckCPUendian() { BigOrLittleData_U Data; Data.uiA = 0x1; return (1 == Data.ucB); /*0 表示大端 1表示小端*/ } int _tmain(int argc, _TCHAR* argv[]) { UINT32 uiCheckFlag = 0; uiCheckFlag = CheckCPUendian(); if (uiCheckFlag) { printf("result: Little endian."); } else { printf("result: Big endian."); } getchar(); return 0; }
#define Big2Little_32(x) ((((x)&0x000000ff)<<24)| \ (((x)&0x0000ff00)<<8) | \ (((x)&0x00ff0000)>>8) | \ (((x)&0xff000000)>>24)) #define Big2Little_16(x) ((((x)&0x00ff)<<8) | \ (((x)&0xff00)>>8)) #define Big2Little_64(x) ((((UINT64)(Big2Little_32((UINT32)(x))))<<32) | \ (Big2Little_32((UINT32)(((UINT64)(x))>>32))))