什么是字节序?
- 内存中多字节值在内存中的存储方式
考虑一个16位整数0x1122
,由两个字节组成,其在内存中有两种存储方法:
网际协议使用大端字节序传送多字节整数
主机字节序判断方法
1. 使用union:
#include<iostream>
using namespace std;
int main()
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x1122;
if(sizeof(short) == 2)
{
if(un.c[0] == 0x11 && un.c[1] == 0x22)
cout << "Big Endian" << endl;
else if(un.c[0] == 0x22 && un.c[1] == 0x11)
cout << "Little Endian" << endl;
else
cout << "unknown" << endl;
}
//c[0]为低地址,c[1]为高地址,11为高八位,22为低八位
else
cout << "short size: " << sizeof(short) << endl;
return 0;
}
在ubuntu15.04,64位中输出为
Little Endian
2. 使用指针的强制类型转换
#include<iostream>
#include<iomanip>
using namespace std;
template<typename t> void showBytes(t &x)
{
int len = sizeof(t);
unsigned char* ptr = reinterpret_cast<unsigned char*>(&x);
//cout << len << endl;
cout << "0x";
for(int i(0); i != len; ++i)
{
cout << setw(2) << setfill('0')
<< hex << static_cast<int>(ptr[i]) << flush;
}
cout << endl;
}
int main()
{
short val = 0x1122;
showBytes(val);
return 0;
}
同样在本机的系统中,输出0x2211
,说明低位在前,高位在后,即本机为小端字节序。