SX_union联合体在项目中的应用_7
创始人
2024-11-14 14:34:05
0

在看项目源码的时候看到了实现某个功能用到了union联合体,仔细分析发现代码非常优雅

代码:

#include  #include  #include   extern uint16_t htons(uint16_t hostshort) __attribute__((const));  int main() {     union {         uint16_t s;         uint8_t buf[sizeof(uint16_t)];     } u_s;      // 初始化联合体     u_s.s = htons((uint16_t)1000);      // 打印结果     printf("u_s.s: %d\n", u_s.s);     printf("size of uint16_t: %d\n", (int)sizeof(uint16_t));     printf("size of int16_t: %d\n", (int)sizeof(int16_t));     printf("u_s.buf: ");     for (int i = sizeof(uint16_t) - 1; i >= 0; i--) {         printf("buf[%d]: %d ", i, u_s.buf[i]);     }     printf("\n"); } 

数字16的16进制表示为0x0010,数字4096的16进制表示为0x1000。 由于Intel机器是小尾端,存储数字16时实际顺序为1000,存储4096时实际顺序为0010。因此在发送网络包时为了报文中数据为0010,需要经过htons进行字节转换。如果用IBM等大尾端机器,则没有这种字节顺序转换,但为了程序的可移植性,也最好用这个函数。

上述的代码就是转换过程:

由于uint8_t是一字节,所以0x0010的前两位00会放在一个下标内,另一个会放在另一个下标内

saisi@ubuntu:~/Desktop/Myproject/socketcmm$ make run ./hton u_s.s :59395 size uint16_t :2 size int16_t :2 us_s.buf: buf[1]:232 buf[0]:3  saisi@ubuntu:~/Desktop/Myproject/socketcmm$ 

232 * 16 * 16 + 3 = 59395
3 * 16 * 16 + 232 = 1000

相关内容

热门资讯

透视教学!wepoker破解器... 透视教学!wepoker破解器有用吗,wepoker安装教程(一贯是有挂)1、进入游戏-大厅左侧-新...
透视总结!aapoker万能辅... 透视总结!aapoker万能辅助器(透视)俱乐部靠谱(总是真的是有挂)1、不需要AI权限,帮助你快速...
透视新版!wepoker轻量版... 透视新版!wepoker轻量版透视,wepoker透视脚本网页(总是是有挂);1)wepoker透视...
透视脚本!aapoker辅助器... 透视脚本!aapoker辅助器是真的吗(透视)脚本可以用(确实是真的有挂)运aapoker辅助器是真...
透视肯定!wepoker脚本下... 透视肯定!wepoker脚本下载,we-poker有人玩吗(原来真的有挂)一、we-poker有人玩...
透视app!aapoker透视... 透视app!aapoker透视脚本(透视)万能辅助器(竟然真的有挂);1、aapoker透视脚本ai...
透视好友房!有没有人wepok... 透视好友房!有没有人wepoker,wepoker作弊视频(一直存在有挂)暗藏猫腻,小编详细说明we...
透视代打!aapoker能控制... 透视代打!aapoker能控制牌吗(透视)辅助(都是真的有挂)1、在aapoker能控制牌吗ai机器...
透视了解!wepoker底牌透... 透视了解!wepoker底牌透视脚本,wepoker怎么挂飞机(本来是真的有挂);1、超多福利:超高...
透视肯定!aapoker透视脚... 透视肯定!aapoker透视脚本下载(透视)透视插件(果然真的有挂)1、玩家可以在aapoker透视...