栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Linux C/C++字节序转换函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux C/C++字节序转换函数

文章目录
  • 一、字节序转换函数
  • 二、使用步骤
  • 总结


一、字节序转换函数

转换端口
uint16_t htons(uint16_t hostshort); //主机字节序->网络字节序
uint16_t ntohs(uint16_t netshort); //网络字节序->主机字节序

转IP
uint32_t htons(uint32_t hostlong);//主机字节序->网络字节序
uint32_t ntohs(uint32_t netlong);//网络字节序->主机字节序

二、使用步骤

#include
#include

int main()
{
    //htons 转换端口
    unsigned short a=0x0102; 
    printf("%xn",a);
    unsigned short b=htons(a);
    printf("%xn",b);

    printf("--------------------------------n");
    //htonl 转换IP
    char buf[4]={192,168,1,100};
    int num=*(int *)buf;
    int res=htonl(num);
    unsigned char* p=(char*)&res;
    printf("%d %d %d %dn",*p,*(p+1),*(p+2),*(p+3));

    printf("--------------------------------n");
    //ntohs
    unsigned char buf1[4]={1,1,168,192};
    int num1=*(int*)buf1;
    int res1=ntohl(num1);
    unsigned char* p1=(unsigned char*)&res1;
    printf("%d %d %d %dn",*p1,*(p1+1),*(p1+2),*(p1+3));

    printf("--------------------------------n");
    //ntohl
    unsigned int c=0x12345678; 
    printf("%xn",c);
    unsigned int d=htonl(c);
    printf("%xn",d);

    return 0;
}

总结

本节主要介绍了字节序转换函数,以便在实际开发中使用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号