定點數
一、介紹
-
定點數與浮點數:
定點數是指小數點在數中的位置是固定保持不變的二進制數。
浮點數分為幾個部分:,其中N表示一個浮點數,Ms表示正負,E表示階碼,R是基數,一般是2,M是尾數。
float point -
為什么要用定點數呢
在硬件數字電路中,許多處理器都是整數處理器,需要用整數運算模擬浮點數運算,所以整數運算要比浮點數更快,所以使用定點數可以提升運算效率。
二、使用
在一些實際使用中,我們開發的一些功能都是使用定點數運算的。所以通過一些寄存器配置的一些參數,都是對應的定點數。所以在實際使用中,要清楚地知道定點數的定點位置,這樣才能得到相應的定點數喂給寄存器。
定點數計算方法,實際上大家自己想想也能得到如下的結果:
/* 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