字节序大小端转换、模拟htons、htonl、ntohs、ntohl

来源:互联网 发布:127.0.0.1 linux 编辑:程序博客网 时间:2024/05/19 04:04
大端模式:一个多字节数据的高字节在前,低字节在后,以数据 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,小端返回falsebool 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);}
阅读全文
0 0
原创粉丝点击