我有一个期望32位浮点数的函数,但是在某种模式下它期望浮点数实际上只是4x UINT8s打包在一起。
我编写的代码有效,但我得到编译器警告“非法指针”警告,我想知道什么是最“正确”的方法呢?代码可读性也非常重要,我认为我写的内容很容易阅读,尽管可能有更少的方法来编写它。
UINT8 time[6];
FLOAT FSTtime = 0; //32bit float
UINT8 * FSTtimePointer;
//Get the current time as 6 bytes {secs,mins,hours,day,month,year}
returnSize = appP->DB_get_param_value(12, 0, 8, &time);
if (returnSize < 6) return;
(UINT8*)FSTtimePointer = &FSTtime; //Line 876
//Pack 4 bytes of time data into a "float"
FSTtimePointer [0] = time[3]; //Reverse month & day because americans are backwards
FSTtimePointer [1] = time[4];
FSTtimePointer [2] = time[2];
FSTtimePointer [3] = time[1];
appP->HIST_write_FST_log(SubMin_CFG.OFFSET, (UINT16)historyPointer, FSTtime);
HIST_write_FST_log的原型是
void (*HIST_write_FST_log) (UINT8 hist_pt_index, UINT16 log_index, FLOAT value);
我得到的编译器警告是:
876: C1000 (W) Illegal pointer assignment
876: C1024 (W) First operand of "=" is not lvalue
如果有人对我正在使用的编译器感兴趣,那就是用于Hitachi处理器的Renesas H8。
答案 0 :(得分:4)
您可以使用修改代码,如下所示
FSTtimePointer =(UINT8 *)&amp; FSTtime;
答案 1 :(得分:2)
您确定这是您想要存储时间的方式吗?浮点数据类型的内部通常不在字节障碍上对齐,日期通常是从纪元开始的秒或毫秒(通常为UINT32
或UINT64
),而不是浮点数 - 点类型。您可能还需要考虑处理器中的MSB或LSB字节顺序。 (免责声明:我不知道Hitachi处理器如何处理字节排序或浮点数据类型。)
如果您确定这是您想要的方式,那么您应该能够使用union
来处理更大数据类型中的各个字节:
union converter_type
{
UNIT8 elements[4];
FLOAT whole;
} converter;
UINT8 time[6];
FLOAT FSTtime = 0; //32bit float
//Get the current time as 6 bytes {secs,mins,hours,day,month,year}
returnSize = appP->DB_get_param_value(12, 0, 8, &time);
if (returnSize < 6) return;
//Pack 4 bytes of time data into a "float"
converter.elements[0] = time[3]; //Reverse month & day because Americans are backwards
converter.elements[1] = time[4]; // (Yes, we are.)
converter.elements[2] = time[2]; // (But what about Canadians? They're "American", too! ;) )
converter.elements[3] = time[1];
FSTtime = converter.whole;
appP->HIST_write_FST_log(SubMin_CFG.OFFSET, (UINT16)historyPointer, FSTtime);