1、16位定点与浮点数相互转换
//浮点转16位定点
void BspFloatToFix16(uchar ucType, uchar ucInteger, uchar ucdecimal, float dbDou, uint16_t * fix)
{
uint16_t lltemp = 0;
uint16_t dbtemp = 0;
dbtemp = dbDou;
if(dbtemp < 0) /* 有符号正数 或者 无符号数 */
{
lltemp = (uint16_t)(-dbDou*(1<<ucdecimal));
*fix = (uint16_t)((uint16_t)(1)<<(ucType + ucInteger + ucdecimal)) - lltemp;
}
else if(dbtemp > 0) /* 有符号负数 */
{
*fix = (uint16_t)(dbDou * (1<<ucdecimal));
}
else
{
*fix = 0;
}
}
void BspFix16ToFloat(uchar ucType, uchar ucInteger, uchar ucdecimal, uint16_t llfix, float *pdbRet)
{
uint16_t lltemp = llfix & ((((uint16_t)(1)<<(ucType + ucInteger + ucdecimal))-1));
if(0 == llfix)
{
*pdbRet = 0.0;
}
if(lltemp & (((uint16_t)(1)<<(ucInteger + ucdecimal)))) /* 有符号数并且是负数 */
{
*pdbRet = -(float)(((uint16_t)(1)<<(ucType + ucInteger + ucdecimal)) - lltemp)/(float)((uint16_t)(1)<<ucdecimal);
}
else /* 无符号数或者有符号数的正数*/
{
*pdbRet = (float)((float)lltemp/(float)((uint16_t)1<<ucdecimal));
}
}
测试代码
float f = -89.5;
uint16_t fix=0;
有符号数,7位整数位,8位小数位
BspFloatToFix16(1,7, 8, f, &fix);
printf("fix:%u\n",fix);
float pdbRet=0;
BspFix16ToFloat(1, 7, 8, fix,&pdbRet);
printf("float:%u\n",pdbRet);
/*<FUNC>***********************************************************************
* 函数名称: BspFixToDou
* 功能描述: 将指定的定点数 转化为 浮点数
* 算法描述: 无
* 输入参数: ucType 0表示无符号 1表示有符号
* ucInteger 表示整数占几个bit
* ucdecimal 表示小数占几个bit
* llfix 为待转化的定点数
* 输出参数: 无
* 返 回 值: 无
************************************************************************/
void BspFixToDou(uchar ucType, uchar ucInteger, uchar ucdecimal, uint64_t llfix, double *pdbRet)
{
uint64_t lltemp = llfix & ((((uint64_t)(1)<<(ucType + ucInteger + ucdecimal))-1));
if(0 == llfix)
{
*pdbRet = 0.0;
}
if(lltemp & (((uint64_t)(1)<<(ucInteger + ucdecimal)))) /* 有符号数并且是负数 */
{
*pdbRet = -(double)(((uint64_t)(1)<<(ucType + ucInteger + ucdecimal)) - lltemp)/(double)((uint64_t)(1)<<ucdecimal);
}
else /* 无符号数或者有符号数的正数*/
{
*pdbRet = (double)((double)lltemp/(double)((uint64_t)1<<ucdecimal));
}
}
/*<FUNC>***********************************************************************
* 函数名称: BspDouToFix
* 功能描述: 将指定的浮点数 转化为 定点数
* 算法描述: 无
* 输入参数: ucType 0表示无符号 1表示有符号
* ucInteger 表示整数占几个bit
* ucdecimal 表示小数占几个bit
* dbDou 为待转化的浮点数
* 输出参数: 无
* 返 回 值: 转化后的定点数
************************************************************************/
void BspDouToFix(uchar ucType, uchar ucInteger, uchar ucdecimal, double dbDou, uint64_t *pllfix)
{
uint64_t lltemp = 0;
double dbtemp = 0;
dbtemp = dbDou;
if(dbtemp < 0) /* 有符号正数 或者 无符号数 */
{
lltemp = (uint64_t)(-dbDou*(1<<ucdecimal));
*pllfix = (uint64_t)((uint64_t)(1)<<(ucType + ucInteger + ucdecimal)) - lltemp;
}
else if(dbtemp > 0) /* 有符号负数 */
{
*pllfix = (uint64_t)(dbDou * (1<<ucdecimal));
}
else
{
*pllfix = 0;
}
}