最近做stm32項目用到一些數據的轉換,現貼出來,大家一起討論:
void float2str(float val, unsigned char Decimal, char *buf)
{
char fmt[]="%.3f";
fmt[2]=Decimal+0x30;
sprintf(buf, fmt, val);
}
void IntToStr(int dat,char *buf)
{
sprintf(buf, "%d", dat);
}
/*
將float類型轉爲uint16數組的指定位置
value:float類型的值
*arr:數組的指針
startpos:開始的位置
*/
void FloatToUint16Array(float value,unsigned short *arr,unsigned short startpos)
{
unsigned short *p = (uint16_t*)&value ; //把float類型的指針強制轉換爲uint16_t型
*(arr+startpos+1)=*p++;
*(arr+startpos)=*p;
}
/*
uint16數組指定位置轉爲float
arr: 源數組
startpos: 開始位置
返回float
*/
float ConventToFloat(unsigned short *arr,unsigned short startpos)
{
float temp;
unsigned short *p = (uint16_t*)&temp; //把float類型的指針強制轉換爲uint16_t型
*p++=*(arr+startpos+1);
// pos++;
*p=*(arr+startpos);
return temp;
}