标题: 单片机C语言如何把高低位整合在一起? [打印本页]

作者: 小丑only    时间: 2022-5-23 08:55
标题: 单片机C语言如何把高低位整合在一起?
U8RH_data_H_temp=U8comdata;    COM();    U8RH_data_L_temp=U8comdata;    COM();    U8T_data_H_temp=U8comdata;    COM();    U8T_data_L_temp=U8comdata;    COM();

作者: lkc8210    时间: 2022-5-23 11:40
U16RH_data_temp = U8RH_data_H_temp;
U16RH_data_temp <<= 8;
U16RH_data_temp |= U8RH_data_L_temp;
作者: lose2836    时间: 2022-5-23 13:35

c习惯这么写,也可以
#include <stdint.h>
uint16_t temp = (uint16_t)(U8RH_data_H_temp<<8) + (uint16_t) U8RH_data_L_temp;

作者: abob    时间: 2022-5-24 09:58
用union
作者: 小丑only    时间: 2022-5-24 11:25
lose2836 发表于 2022-5-23 13:35
c习惯这么写,也可以
#include
uint16_t temp = (uint16_t)(U8RH_data_H_temp

写的仔细,学习了。谢谢
作者: Hephaestus    时间: 2022-5-24 11:36
移位太浪费时间了,用union或者指针操作。
作者: lkc8210    时间: 2022-5-24 14:12
Hephaestus 发表于 2022-5-24 11:36
移位太浪费时间了,用union或者指针操作。

我想到的指针用法是这样,请指教
  1. #include <reg52.h>

  2. typedef         unsigned char        u8;  //0 to 255
  3. typedef         unsigned int        u16;  //0 to 65535
  4. typedef         unsigned long        u32;  //0 to 4294967295

  5. u8 U8RH_data_temp[2] = {0x12, 0x23};//{High Byte, Low Byte}
  6. u16 *U16RH_data_temp;

  7. void main()
  8. {
  9.                 U16RH_data_temp = (u16*)U8RH_data_temp;
  10.     while (1)
  11.     {
  12.     }
  13. }
复制代码




作者: glinfei    时间: 2022-5-24 14:35
union U16_union
{
unsigned int U16RH_data_temp;
unsigned char U8RH_H,U8RH_L;
} U16_data;
U16_data.U8RH_H= U8RH_data_H_temp;
U16_data.U8RH_L= U8RH_data_L_temp;
U16_data.U16RH_data_temp     //你要的合并的值,但这个用法跟芯片大小数有关,51没问题
作者: 188610329    时间: 2022-5-24 14:53
sfr  DPL = 0x82;
sfr  DPH = 0x83;
sfr16 DPTR = 0x82;
unsigned char testbyte_H = 0x12;   //8位
unsigned char testbyte_L = 0x34;   //8位
unsigned short testword;        //16位

void main()
{
            DPL = testbyte_L;          //存入低8位字节
            DPH = testbyte_H;        //存入高8位字节

            testword = DPTR;    //读出 16位 字
            while(1);
}
作者: Hephaestus    时间: 2022-5-24 17:08
lkc8210 发表于 2022-5-24 14:12
我想到的指针用法是这样,请指教

可以用,但是要注意大小端问题。8位单片机本身不存在大小端问题,但是编译器会给超过1个字节的数据按大端和小端来分配地址。
作者: yaoyao2022    时间: 2022-5-24 20:49
可以使用共用体
作者: lkc8210    时间: 2022-5-24 21:37
Hephaestus 发表于 2022-5-24 17:08
可以用,但是要注意大小端问题。8位单片机本身不存在大小端问题,但是编译器会给超过1个字节的数据按大端 ...

受教了~
作者: hy47566398    时间: 2022-5-25 00:24
U16 data_Value = u8_HIGH * 0x100 + u8_LOW





欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1