Defining (1 << 31) or using 0x80000000? Result is different

前端 未结 3 1790
暗喜
暗喜 2021-01-18 11:31
#define SCALE (1 << 31)

#define fix_Q31_80(x) ( (int) ( (float)(x)*(float)0x80000000 ) )
#define fix_Q31_SC(x) ( (int) ( (float)(x)*(float)SCALE      ) )

int         


        
3条回答
  •  渐次进展
    2021-01-18 12:04

    0x80000000 is a big number which needs 32 bit to represent that number. This means on a 32 bit system (or in a 32 bit compatible application) an int is too small. So use unsigned long instead:

    #define SCALE (1u << 31)
    
    #define fix_Q31_80(x) ( (unsigned long) ( (float)(x)*(float)0x80000000u ) )
    #define fix_Q31_SC(x) ( (unsigned long) ( (float)(x)*(float)SCALE       ) )
    
    int main()
    {
        unsigned long fix_80 = fix_Q31_80(0.5f);
        unsigned long fix_sc = fix_Q31_SC(0.5f);
    }
    

提交回复
热议问题