简体   繁体   中英

Avoiding redundancy in C macros

I am having some redundancy in C code, which I would like to avoid.

// Q15 macros
#define SCALE_FACTOR_Q15 ( 0x00008000UL )
#define Q15_MAX          ( 0x00007FFFUL )
#define f32_Q15_x(x)     ( (f32)(int) ( (float)(x)*(float)SCALE_FACTOR_Q15 ) )
#define f32_Q15_MAX      ( (f32)      ( Q15_MAX )                            )
// etc...

// Q31 macros
#define SCALE_FACTOR_Q31 ( 0x80000000UL )
#define Q31_MAX          ( 0x7FFFFFFFUL )
#define f32_Q31_x(x)     ( (f32)(int) ( (float)(x)*(float)SCALE_FACTOR_Q31 ) )
#define f32_Q31_MAX      ( (f32)      ( Q31_MAX )                            )
// etc...

Now I need to do the same peace of code for Q25 , and in the future probably for other Qx , where x is in range [1,63] .

How could I avoid writing this separately for each Qx ?

How about this?

#define SCALE_FACTOR_Q(N) ( 1UL << N )
#define Q_MAX(N)          ( SCALE_FACTOR_Q(N) - 1 )
#define f32_Q_x(N,x)      ( (f32)(int) ( (float)(x)*(float)SCALE_FACTOR_Q(N) ) )
#define f32_Q_MAX(N)      ( (f32)Q_MAX(N) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM