zoukankan      html  css  js  c++  java
  • 实现两个字节序的交换

    实现两个字节序的交换例如: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
    ",b);
    22     
    23     return 0;
    24 }

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

      uint16_t      Temperature;

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

  • 相关阅读:
    Django【进阶】信号
    Django【进阶】缓存
    exec,eval
    linux下磁盘分区、格式化、挂载
    Django【进阶】中间件
    Django【进阶】权限管理
    Django【进阶】FBV 和 CBV
    MySQL 进阶(待发布)
    Django【进阶】
    django 分页和中间件
  • 原文地址:https://www.cnblogs.com/prayer521/p/5879806.html
Copyright © 2011-2022 走看看