栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

大小端与网络字节序

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

大小端与网络字节序

1.大小端
大端字节序:高地址储存在低位
小端字节序:高地址存储在高位
2.判断
#include 
int main()
{
    int a = 1;
    char ch = *(char*)&a;
    if(ch)
        printf("littlen");
    else
        printf("bign");
  
    return 0;
}
3.共用体判断
#include 
union
{
  char ch;
  int a;
}un;
int main()
{
   un.a = 0x12345678;
  
   if(ui.ch == 0x12)
       printf("bign");
    else
        printf("littlen");
  
    return 0; 
}
4.网络字节序
  • 网络上传输的数据都是{% label 字节流 blue %},对于一个多字节的数值的传输,先传输那个字节?接受端接收的第一个字节作为高字节还是低字节?
//UDP/TCP/IP协议规定,把接收到的第一个字节作为高字节看待,也就是网络字节序是大端字节序

  
//字节序转换函数
  
#include 

//主机字节序转化为网络字节序
unit32_t htonl (unit32_t hostlong);
unit16_t htons (unit16_t hostshort);

//网络字节序转化为主机字节序
unit32_t ntohl (unit32_t netlong);
unit16_t ntohs (unit16_t netshort);

  
#include 
#include 

int main()
{
    unsigned int x = 0x12345678;
    unsigned char *p = (unsigned char *)&x;
    printf("%0x_%0x_%0x_%0xn",p[0],p[1],p[2],p[3]);
  
    unsigned int y = htonl(x);
    p = (unsigned char*)&y;
    printf("%0x_%0x_%0x_%0xn",p[0],p[1],p[2],p[3]);
  
    return 0;
}


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

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

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