大端模式:一个多字节数据的高字节在前,低字节在后,以数据 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 )
bool checkCPUendian()
{
union
{
unsigned long int i;
unsigned char s[4 ];
}c;
c.i = 0x12345678 ;
return (0x12 == c.s [4 ]);
}
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);
}