函数说明
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
/*
h表示host,n表示network,l表示32位长整数,s表示16位短整数。
如果主机是小端字节序,这些函数将参数做相应的大小端转换然后返回,如果主机是大端字节序,这些函数不做转换,将参数原封不动地返回。
*/
windows下
如果是VS,包含头文件及ws2_32.lib库
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")
如果是QtCreator,包含头文件及ws2_32.lib
.pro中:
LIBS += -LC:\Users\HHT\Desktop\serialPort\ -lWS2_32
其中,C:\Users\HHT\Desktop\serialPort\ 是ws2_32.lib所在路径。
cpp文件:
#include <winsock.h>
测试代码:
unsigned short test1 = htons(0xffee);
cout << 0xffee << endl;
cout << test1 << endl;//转换后为0xeeff
unsigned int test2 = htonl(0xaaeeeeee);
cout << 0xaaeeeeee << endl;
cout << test2 << endl;//转换后为0xeeeeeeaa
Linux(Ubuntu)下
在QtCreator中测试
头文件
#include <arpa/inet.h>
测试代码:
qDebug()<<"htons:"<<htons(0xffee);
qDebug()<<"htonl:"<<htonl(0xaaeeeeee);
判断系统种变量高\低字节在前
#include <stdio.h>
#include <memory.h>
void main()
{
int a=10;
short b;
memcpy(&b,&a,2);
printf("%d\n",b);
}
参考
大端模式和小端模式
发送到串口的数据,串口接收是相反的?
详解C语言的htons函数
大小端及网络字节序
字节顺序的问题(高位在前&低位在前)
如何判断变量在内存中如何放置的?低位在前还是高位在前
高低字节序转换(htonl、ntohl、 htons、ntohs函数)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)