定点数

定点数

一、介绍

  1. 定点数与浮点数:
    定点数是指小数点在数中的位置是固定保持不变的二进制数。
    浮点数分为几个部分:,其中N表示一个浮点数,Ms表示正负,E表示阶码,R是基数,一般是2,M是尾数。

    float point
    float point

  2. 为什么要用定点数呢

在硬件数字电路中,许多处理器都是整数处理器,需要用整数运算模拟浮点数运算,所以整数运算要比浮点数更快,所以使用定点数可以提升运算效率。

二、使用

在一些实际使用中,我们开发的一些功能都是使用定点数运算的。所以通过一些寄存器配置的一些参数,都是对应的定点数。所以在实际使用中,要清楚地知道定点数的定点位置,这样才能得到相应的定点数喂给寄存器。

定点数计算方法,实际上大家自己想想也能得到如下的结果:

/* The basic operations performed on two numbers a and b of fixed point q
format returning the answer in q format */

#define FADD(a, b)     ((a) + (b))
#define FSUB(a, b)     ((a) - (b))
//#define FMUL(a, b, q)  (((a)*(b))>>(q))
#define FMUL(a, b, q)  ((long)((a)*(b))>>(q))
#define FDIV(a, b, q)  (((a)<<(q))/(b))


/* The basic operation where a is of fixed point q format and b is
an integer */

#define FADDI(a, b, q)  ((a) + ((b)<<(q)))
#define FSUBI(a, b, q) ((a) - ((b)<<(q)))
#define FMULI(a, b)    ((a)*(b))
#define FDIVI(a, b)    ((a)/(b))


/* convert a from q1 format to q2 format */

#define FCONV(a, q1, q2)  (((q2) > (q1)) ? (a)<<((q2)-(q1)) : (a)>>((q1) - (q2)))

/* the general operation between a in q1 format and b in q2 format
returning the result in q3 format */

#define FADDG(a, b, q1, q2, q3)  (FCONV(a, q1, q3) + FCONV(b, q2, q3))
#define FSUBG(a, b, q1, q2, q3)  (FCONV(a, q1, q3) - FCONV(b, q2, q3))
#define FMULG(a, b, q1, q2, q3)   FCONV((a)*(b), (q1)+(q2), q3)
#define FDIVG(a, b, q1, q2, q3)  (FCONV(a, q1, (q2) + (q3))/(b))


/* convert to and from floating point */
#define TOFIX(d, q)  ((int) ( (d)*(double) (1<<(q)) ))
#define TOFLT(a, q)  (  (double)(a) / (double)(1<<(q)) )

Reference

https://blog.csdn.net/whoisleft/article/details/77417541
https://blog.csdn.net/u013580397/article/details/80878213

原文地址:https://www.cnblogs.com/gr-nick/p/10805534.html