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

大端模式:一个多字节数据的高字节在前,低字节在后,以数据 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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
这几个函数都是用来进行网络字节和主机字节之间的转换的。 - `htonl` (Host TO Network Long):将一个 32 位的主机字节整数转换为网络字节整数。如果主机字节是大字节,则不做任何改变;如果主机字节是小字节,则将其转换为大字节。返回网络字节整数。 ```c++ #include <arpa/inet.h> uint32_t htonl(uint32_t hostlong); ``` - `htons` (Host TO Network Short):将一个 16 位的主机字节整数转换为网络字节整数。如果主机字节是大字节,则不做任何改变;如果主机字节是小字节,则将其转换为大字节。返回网络字节整数。 ```c++ #include <arpa/inet.h> uint16_t htons(uint16_t hostshort); ``` - `ntohl` (Network TO Host Long):将一个 32 位的网络字节整数转换为主机字节整数。如果当前主机字节是大字节,则不做任何改变;如果当前主机字节是小字节,则将其转换为小字节。返回主机字节整数。 ```c++ #include <arpa/inet.h> uint32_t ntohl(uint32_t netlong); ``` - `ntohs` (Network TO Host Short):将一个 16 位的网络字节整数转换为主机字节整数。如果当前主机字节是大字节,则不做任何改变;如果当前主机字节是小字节,则将其转换为小字节。返回主机字节整数。 ```c++ #include <arpa/inet.h> uint16_t ntohs(uint16_t netshort); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值