http://blog.youkuaiyun.com/hongqun/article/details/6092210
大端法、小端法、网络字节序
转自博客园
关于字节序(大端法、小端法)的定义
《UNXI网络编程》定义:术语“小端”和“大端”表示多字节值的哪一端(小端或大端)存储在该值的起始地址。小端存在起始地址,即是小端字节序;大端存在起始地址,即是大端字节序。
也可以说:
1.小端法(Little-Endian)就是低位字节排放在内存的低地址端即该值的起始地址,高位字节排放在内存的高地址端。
2.大端法(Big-Endian)就是高位字节排放在内存的低地址端即该值的起始地址,低位字节排放在内存的高地址端。
举个简单的例子,对于整形0x12345678。它在大端法和小端法的系统内中,分别如图1所示的方式存放。
网络字节序
我们知道网络上的数据流是字节流,对于一个多字节数值,在进行网络传输的时候,先传递哪个字节?也就是说,当接收端收到第一个字节的时候,它是将这个字节作为高位还是低位来处理呢?
网络字节序定义:收到的第一个字节被当作高位看待,这就要求发送端发送的第一个字节应当是高位。而在发送端发送数据时,发送的第一个字节是该数字在内存中起始地址对应的字节。可见多字节数值在发送前,在内存中数值应该以大端法存放。
网络字节序说是大端字节序。
比如我们经过网络发送0x12345678这个整形,在80X86平台中,它是以小端法存放的,在发送前需要使用系统提供的htonl将其转换成大端法存放,如图2所示。
字节序测试程序
不同cpu平台上字节序通常也不一样,下面写个简单的C程序,它可以测试不同平台上的字节序。
#include
#include
int main()
{
int i_num = 0x12345678;
printf("[0]:0x%x\n", *((char *)&i_num + 0));
printf("[1]:0x%x\n", *((char *)&i_num + 1));
printf("[2]:0x%x\n", *((char *)&i_num + 2));
printf("[3]:0x%x\n", *((char *)&i_num + 3));
i_num = htonl(i_num);
printf("[0]:0x%x\n", *((char *)&i_num + 0));
printf("[1]:0x%x\n", *((char *)&i_num + 1));
printf("[2]:0x%x\n", *((char *)&i_num + 2));
printf("[3]:0x%x\n", *((char *)&i_num + 3));
return 0;
}
在80X86CPU平台上,执行该程序得到如下结果:
[0]:0x78
[1]:0x56
[2]:0x34
[3]:0x12
[0]:0x12
[1]:0x34
[2]:0x56
[3]:0x78
分析结果,在80X86平台上,系统将多字节中的低位存储在变量起始地址,使用小端法。htonl将i_num转换成网络字节序,可见网络字节序是大端法。
总结点:80X86使用小端法,网络字节序使用大端法。
评注:
库函数提供了16,32位整型int的网络字节序与本地字节序的转换函数:
NAME
htonl, htons, ntohl, ntohs - convert values between host and network byte order
SYNOPSIS
#include
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
DESCRIPTION
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.
The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.
On the i80x86 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.
对于8字节的long, long long我们可以自己实现一个,下面是一个参考实现方案:
//判断当前环境是否是大端
inline bool isBigEndian()
{
int one = 1;
return (*(char *)&one == 0);
}
//网络转为本地
long nt2hll(long val)
{
if (isBigEndian())
{
return val;
}
char *p = (char*) &val;
char c = 0;
for (int i = 0; i < 4; i++)
{
c = p[i];
p[i] = p[static_cast<unsigned int>(7-i)];
p[static_cast<unsigned int>(7-i)] = c;
}
return val;
}
//本地转为网络
long h2ntll(long val)
{
if (isBigEndian())
{
return val;
}
char *p = (char*) &val;
char c = 0;
for (int i = 0; i < 4; i++)
{
c = p[i];
p[i] = p[static_cast<unsigned int>(7-i)];
p[static_cast<unsigned int>(7-i)] = c;
}
return val;