htonl、ntohl、htons、ntohs函数实现
2016-07-21 11:41
489 查看
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))
// 本机大端返回1,小端返回0
int checkCPUendian()
{
union{
unsigned
long int i;
unsigned
char s[4];
}c;
c.i = 0x12345678;
return (0x12
== c.s[0]);
}
// 模拟htonl函数,本机字节序转网络字节序
unsigned long int t_htonl(unsigned
long int h)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,转换成大端再返回
return checkCPUendian()
? h : BigLittleSwap32(h);
}
// 模拟ntohl函数,网络字节序转本机字节序
unsigned long int t_ntohl(unsigned
long int n)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,网络数据转换成小端再返回
return checkCPUendian()
? n : BigLittleSwap32(n);
}
// 模拟htons函数,本机字节序转网络字节序
unsigned short int t_htons(unsigned
short int h)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,转换成大端再返回
return checkCPUendian()
? h : BigLittleSwap16(h);
}
// 模拟ntohs函数,网络字节序转本机字节序
unsigned short int t_ntohs(unsigned
short int n)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,网络数据转换成小端再返回
return checkCPUendian()
? n : BigLittleSwap16(n);
}
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))
// 本机大端返回1,小端返回0
int checkCPUendian()
{
union{
unsigned
long int i;
unsigned
char s[4];
}c;
c.i = 0x12345678;
return (0x12
== c.s[0]);
}
// 模拟htonl函数,本机字节序转网络字节序
unsigned long int t_htonl(unsigned
long int h)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,转换成大端再返回
return checkCPUendian()
? h : BigLittleSwap32(h);
}
// 模拟ntohl函数,网络字节序转本机字节序
unsigned long int t_ntohl(unsigned
long int n)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,网络数据转换成小端再返回
return checkCPUendian()
? n : BigLittleSwap32(n);
}
// 模拟htons函数,本机字节序转网络字节序
unsigned short int t_htons(unsigned
short int h)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,转换成大端再返回
return checkCPUendian()
? h : BigLittleSwap16(h);
}
// 模拟ntohs函数,网络字节序转本机字节序
unsigned short int t_ntohs(unsigned
short int n)
{
// 若本机为大端,与网络字节序同,直接返回
// 若本机为小端,网络数据转换成小端再返回
return checkCPUendian()
? n : BigLittleSwap16(n);
}
相关文章推荐
- htons和htonl引发的惨案
- XCode下编译RabbitMQ无法通过问题的解决方式
- htons htonl
- python通过ntohl和htonl等函数实现主机字节序和网络字节序相互转换
- 主机序和网络序转换
- 计算机网络难点总结
- ntohs, ntohl, htons,htonl的比较和详解
- 网络大小端转换函数
- 关闭所有activity
- Matlab中的CVX工具包安装
- Golang Unit Test单元测试
- openstack安装配置(二)
- Linux内存管理原理 与文件读写 图 相当详细
- 仿时光轴留言特效
- Navicat for mysql 显示中文乱码问题
- Codeforces Round #363 (Div. 2)->C. Vacations
- habse的CopyTable
- how to send mail from 3rd
- 使用Spring框架的12个开源项目
- 虚拟机svn服务器搭建 Windows下使用VisualSVN Server搭建SVN服务器