位元組序大小端轉換、模擬htons、htonl、ntohs、ntohl
阿新 • • 發佈:2019-02-11
大端模式:一個多位元組資料的高位元組在前,低位元組在後,以資料 0x1234ABCD 看例子: 低地址 ---------------------> 高地址 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 12 | 34 | AB | CD | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 小端模式:一個多位元組資料的低位元組在前,高位元組在後,仍以 0x1234ABCD 看: 低地址 ---------------------> 高地址 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- | CD | AB | 34 | 12 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
typedef unsigned short int uint16;
typedef unsigned long int uint32;
#define BigLittleSwap16(A) ((((uint16)(A) & 0xff00)>>8)|\
(((uint16)(A) & 0x00ff)<<8))
#define BigLittleSwap32(A) (((uint32)(A) & 0xff000000) >> 24)|\
(((uint32 )(A) & 0x00ff0000) >> 8)|\
(((uint32)(A) & 0x0000ff00) << 8)|\
(((uint32)(A) & 0x000000ff) << 24)
//本機大端返回true,小端返回false
bool checkCPUendian()
{
union
{
unsigned long int i;
unsigned char s[4];
}c;
c.i = 0x12345678 ;
return (0x12 == c.s[4]);
}
// 模擬htonl 本機位元組序轉網路位元組序
// 若本機為大端,與網路位元組序相同,直接返回
// 若本機為小端,轉換成大端再返回
unsigned long int htonl(unsigned long int h)
{
return checkCPUendian() ? h : BigLittleSwap32(h);
}
unsigned long int ntohl(unsigned long int n)
{
return checkCPUendian() ? n : BigLittleSwap32(n);
}
unsigned short int htons(unsigned short int h)
{
return checkCPUendian() ? h : BigLittleSwap16(h);
}
unsigned short int ntohs(unsigned short int n)
{
return checkCPUendian() ? n : BigLittleSwap16(n);
}