# 字节存储排序：大端(big endian)和小端(little)的判别及转换

1.大端和小端的方式及判断

0x12345678   16进制，两个数就是一字节

低地址位     高低址位

#include <iostream>

using namespace std;

typedef unsigned int UINT;
typedef unsigned char UCHAR;

int main()
{
UINT i=0x12345678;
cout<<hex<<i<<endl;
UCHAR *p = (UCHAR*)&i;          <span style="color:#33cc00;">//将i的地址传给数组指针p，实际上p指向的地址是i在内存中存储的第一个字节，大端就是0x12，小端就是0x78</span>
if((*p==0x78)&(*(p+1)==0x56))
cout<<"小端"<<endl;
else if((*p==0x12)&(*(p+1)==0x34))
cout<<"大端"<<endl;
else
cout<<"这是神马字节顺序呢？";
return 0;
}

2.大端和小端的字节转换

#include <iostream>

using namespace std;

typedef unsigned int UINT;
typedef unsigned char UCHAR;

int main()
{
UINT i=0x12345678;
cout<<hex<<i<<endl;
UCHAR *p = (UCHAR*)&i;
UINT num,num1,num2,num3,num4;
num1=(UINT)(*p)<<24;
num2=((UINT)*(p+1))<<16;
num3=((UINT)*(p+2))<<8;
num4=((UINT)*(p+3));
num=num1+num2+num3+num4;

cout<<"num1:"<<hex<<num1<<endl;     <span style="color:#33ff33;">//看num1的16进制表示，下同</span>
cout<<"num2:"<<hex<<num2<<endl;
cout<<"num3:"<<hex<<num3<<endl;
cout<<"num4:"<<hex<<num4<<endl;
cout<<"num:"<<hex<<num<<endl;

unsigned char *q = (unsigned char*)#
if((*q==0x78)&(*(q+1)==0x56))
cout<<"小端"<<endl;
else if((*q==0x12)&(*(q+1)==0x34))
cout<<"大端"<<endl;
else
cout<<"这是神马字节顺序呢？";
return 0;
}

UINT EndianConvertLToB(UINT InputNum) {
UCHAR *p = (UCHAR*)&InputNum;
return(((UINT)*p<<24)+((UINT)*(p+1)<<16)+
((UINT)*(p+2)<<8)+(UINT)*(p+3));
}

UINT EndianConvertBToL(UINT InputNum) {
UCHAR *p = (UCHAR*)&InputNum;
return(((UINT)*p)+((UINT)*(p+1)<<8)+
((UINT)*(p+2)<<16)+(UINT)*(p+3)<<24);
}

10-26 2001

01-17 1178

12-17 548

05-04 3488

09-27 1387

09-28 583

06-06 111

01-12 259

02-22 2210

06-14 3498