大小端与网络字节序

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

  
//字节序转换函数
  
#include <arpa/inet.h>

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

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

/*
h--host
n--network
s--short--PORT
l--long--IP
*/  
#include <stdio.h>
#include <arpa/inet.h>

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


//output
78_56_34_12
12_34_56_78
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值