码迷,mamicode.com
首页 > 其他好文 > 详细

实现两个字节序的交换

时间:2016-09-17 23:31:30      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

实现两个字节序的交换例如:300=0X012C,交换之后为0X2C01

 1 /*******************************************************************************
 2 * Function Name  : exchangeBytes
 3 * Description    : 模拟的htons 或者 ntohs,如果系统支字节序更改可直接替换成系统函数
 4 * Input          : value
 5 * Output         : None
 6 * Return         : 更改过字节序的short数值
 7 * Attention           : None
 8 *******************************************************************************/
 9 short    exchangeBytes(short    value)
10 {
11     short            tmp_value;
12     uint8_t        *index_1, *index_2;
13 
14     index_1 = (uint8_t *)&tmp_value;
15     index_2 = (uint8_t *)&value;
16 
17     *index_1 = *(index_2+1);
18     *(index_1+1) = *index_2;
19 
20     return tmp_value;
21 }

测试代码

 1 #include <stdio.h>
 2 typedef unsigned char  uint8_t;
 3 short    exchangeBytes(short    value)
 4 {
 5     short            tmp_value;
 6     uint8_t        *index_1, *index_2;
 7 
 8     index_1 = (uint8_t *)&tmp_value;
 9     index_2 = (uint8_t *)&value;
10 
11     *index_1 = *(index_2+1);
12     *(index_1+1) = *index_2;
13 
14     return tmp_value;
15 }
16 int main(void)
17 {
18     short a=300;
19     short b=0;
20     b=exchangeBytes(300);
21     printf("b=%d\n",b);
22     
23     return 0;
24 }

 机智云传两个字节类型的温度数据时由于其数据类型定义为:

  uint16_t      Temperature;

而网络字节序就是大端字节序,MDK中默认的是小端所以须将其转换为大端字节序:ReadTypeDef.Temperature = exchangeBytes(300);

 

实现两个字节序的交换

标签:

原文地址:http://www.cnblogs.com/prayer521/p/5879806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!