1、 字节顺序概念
字节顺序是指占内存多于一个字节类型的数据在内存中的存放顺序,通常有小端、大端两种字节顺序。
大端对齐:内存的低地址位存放着高位数据;
小端对齐:内存的低地址位存放着低位数据;
举个例子,内存中两个连续字节中的数据为0x12 0x34,表示一个short,如果是大端对齐,这个数为0x1234;如果是小端对齐,则这个数为0x3412。
2、 测试代码
/*对psString里面的内存数据做,高字节在前,低字节在后的处理,如果只用用int强转,由于Linux是小端对齐会出现问题,所以要做特别处理*/
unsigned int _Api_ToolChar2Long(char *psString, int iStrLen, unsigned int *pulOut)
{
int iCnt;
unsigned long ulTmp,ulValue;
ulTmp = 0L;
for(iCnt = 0; iCnt < iStrLen; iCnt++)
{
ulValue = (unsigned long)psString[iCnt] & 0xFF;
ulTmp |= ( ulValue << 8 * (iStrLen - iCnt - 1));
}
if (pulOut != NULL)
{
*pulOut = ulTmp;
}
return ulTmp;
}
int main(int argc, char **argv)
{ int i = 10;
int j = 0;
int x= 0;
char *pstr =NULL;
char acBuffer[4] = {"\x00\x00\x00\x0a"};
/*查看i在linux下的存放顺序*/
pstr = &i;
for(j = 0; j < 4; j++)
printf("%s, %d, pstr[%d] = 0x%02x\n", __FUNCTION__, __LINE__,j, pstr[j]);
/*查看网络字节序的存放顺序*/
x = htonl(i);
pstr = &x;
for(j = 0; j < 4; j++)
printf("%s, %d, pstr[%d] = 0x%02x, x = %d\n", __FUNCTION__, __LINE__,j, pstr[j], x);
/*看看这种字节序的输出值*/
i = *(int *)acBuffer;
printf("%s, %d, i = %d\n", __FUNCTION__, __LINE__, i);
/*对acBuffer存放的字节序做特别处理,让它输出10*/
Char2Long(acBuffer,4, &i);
printf("%s, %d, i = %d\n", __FUNCTION__, __LINE__, i);
return 0;
}
2、 输出结果
/*i在内存中的存放顺序,低位在前高位在后*/
main, 87, pstr[0] = 0x0a
main, 87, pstr[1] = 0x00
main, 87, pstr[2] = 0x00
main, 87, pstr[3] = 0x00
/*网络字节序转换后,高位在前低位在后了。输出的值就不正常了*/
main, 92, pstr[0] = 0x00, x = 167772160
main, 92, pstr[1] = 0x00, x = 167772160
main, 92, pstr[2] = 0x00, x = 167772160
main, 92, pstr[3] = 0x0a, x = 167772160
/*同上面网络字节序转换后的结果*/
main, 96, i = 167772160/*自身编写的代码完成了想要的结果*/
main, 102, i = 10
2、 linux网络字节序
BYTEORDER(3)
Linux Programmer's Manual BYTEORDER(3)
NAME
htonl, htons, ntohl, ntohs - convert values between host and network
byte order
SYNOPSIS
#include <arpa/inet.h>
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 i386 the host byte order is Least Significant Byte
first,
whereas the network byte order, as used on the Internet, is Most Sig-
nificant Byte first.
网络编程在Linux中一定要记着用这几个函数来转换成网络字节序。否则会出问题的哦。比如:saddr->sin_port = htons(port);