cpp
#include<stdio.h>
#define uint8_t unsigned char
#define uint16_t unsigned short
#define uint24_t unsigned int
#define uint32_t unsigned int
#define uint64_t unsigned long long
//用户自定义变量名字,用于存储
typedef enum
{
first_run = 0,//1字节
hot_level,
hot_level_end = hot_level+1,//2字节 u16
water_value,
water_value_end = water_value+2, //3字节 u24
coffee_value,
coffee_value_end = coffee_value+3,//4字节 u32
MAX_VAR_LEN,//Keep it last
}TagEnumVar;
uint8_t g_var[MAX_VAR_LEN];
void get_var_u8(TagEnumVar id,uint8_t* value_out )
{
*value_out = g_var[id];
}
void get_var_u16(TagEnumVar id,uint16_t* value_out )
{
*value_out = g_var[id] | (g_var[id+1]<<8);
}
void get_var_u24(TagEnumVar id,uint32_t* value_out )
{
*value_out = g_var[id] | (g_var[id+1]<<8) | (g_var[id+2]<<16);
}
void get_var_u32(TagEnumVar id,uint32_t* value_out )
{
*value_out = g_var[id] | (g_var[id+1]<<8) | (g_var[id+2]<<16) | (g_var[id+3]<<24);
}
void set_var_u8(TagEnumVar id,uint8_t value_out )
{
g_var[id]=value_out;
}
void set_var_u16(TagEnumVar id,uint16_t value_out )
{
g_var[id]=(value_out)&0xFF;
g_var[id+1]=(value_out>>8)&0xFF;
}
void set_var_u24(TagEnumVar id,uint32_t value_out )
{
g_var[id]=(value_out)&0xFF;
g_var[id+1]=(value_out>>8)&0xFF;
g_var[id+2]=(value_out>>16)&0xFF;
}
void set_var_u32(TagEnumVar id,uint32_t value_out )
{
g_var[id]=(value_out)&0xFF;
g_var[id+1]=(value_out>>8)&0xFF;
g_var[id+2]=(value_out>>16)&0xFF;
g_var[id+3]=(value_out>>24)&0xFF;
}
int main()
{
printf("=======C_BuildTime=[%s_%s]==============\r\n\r\n",__DATE__ ,__TIME__ );
uint32_t value_in = 0x12345678;
uint32_t value_out = 0x00;
//先将数据写入,然后读出来看看是否一致
set_var_u8(first_run,(uint8_t)value_in);
get_var_u8(first_run,(uint8_t*)&value_out);
printf("get u8,first_run=0x%x.\n",value_out);//测试8位数据的读和写
set_var_u16(hot_level,(uint16_t)value_in);
get_var_u16(hot_level,(uint16_t*)&value_out);
printf("get u16,hot_level=0x%x.\n",value_out);//测试16位数据的读和写
set_var_u24(water_value,(uint32_t)value_in);
get_var_u24(water_value,(uint32_t*)&value_out);
printf("get u24,water_value=0x%x.\n",value_out);//测试24位数据的读和写
set_var_u32(coffee_value,(uint32_t)value_in);
get_var_u32(coffee_value,(uint32_t*)&value_out);
printf("get u32,coffee_value=0x%x.\n",value_out);//测试32位数据的读和写
return 0;
}
运行效果:[注意变量的位数]