小端字节序:将低字节存在高地址
大端字节序:将高字节存在高地址
Windows默认时小端字节序,可以看一下VS debug时的内存截图。
如何判断机器的字节序
#include <iostream>
using namespace std;
bool checkLitteEndian()
{
int a = 0x01;
unsigned char * pBuff = (unsigned char *)&a;
return pBuff[0] == 0x01;
}
int main(int argc, char* argv[])
{
if (checkLitteEndian())
{
cout << "this is little endian" << endl;
}
else
{
cout << "this is big endian" << endl;
}
return 0;
}
windows 运行结果
网络字节序:
在网络传输时,采用的时大端字节序,在进行网络传输时,要对int等类型进行字节序转换,主要函数如下:
主机字节序转换成网络字节序:htons htonl
网络字节序转换成主机字节序:ntohs ntohl