簡體   English   中英

定點數的乘法

[英]Multiplication of fixed point numbers

我有一個非常基本的問題。 在我的程序中,我正在做兩個定點數的乘法,如下所示。 我的輸入是 Q1.31 格式,輸出也應該是相同的格式。 為了做到這一點,我將乘法的結果存儲在一個臨時的 64 位變量中,然后執行一些操作以獲得所需格式的結果。

int conversion1(float input, int Q_FORMAT)
{
return ((int)(input * ((1 << Q_FORMAT)-1)));
}

int mul(int input1, int input2, int format)
{
    __int64 result;
    result = (__int64)input1 * (__int64)input2;//Q2.62 format
    result = result << 1;//Q1.63 format
    result = result >> (format + 1);//33.31 format
    return (int)result;//Q1.31 format
}

int main()
{
    int Q_FORMAT = 31;
    float input1 = 0.5, input2 = 0.5;
    int q_input1, q_input2;
    int temp_mul;
    float q_muls;

    q_input1 = conversion1(input1, Q_FORMAT);
    q_input2 = conversion1(input2, Q_FORMAT);
    q_muls = ((float)temp_mul / ((1 << (Q_FORMAT)) - 1));
    printf("result of multiplication using q format = %f\n", q_muls);
    return 0; 
}

 My question is while converting float input to integer input (and also while converting int output 
 to float output), i am using (1<<Q_FORMAT)-1 format. But i have seen people using (1<<Q_FORMAT) 
 directly in their codes. The Problem i am facing when using (1<<Q_FORMAT) is i am getting the 
 negative of the desired result.

例如,在我的程序中,

 If i use (1<<Q_FORMAT), i am getting -0.25 as the result
 But, if i use (1<<Q_FORMAT)-1, i am getting 0.25 as the result which is correct.

我哪里出錯了? 我需要理解任何其他概念嗎?

在常見平台上, int是一個二進制補碼 32 位整數,提供 31 位數字(加上一個“符號”位)。 表示需要 32 位數字(加上一個“符號”位)的 Q1.31 數字有點太窄了。

在您的示例中,這表現為表達式1 << Q_FORMAT中的有效算術溢出。

為了避免這種情況,您需要使用提供更多數字的類型(例如long long )或需要更少數字的定點格式(例如 Q1.30 )。 您可以使用unsigned來修復您的示例,但結果將是一個比 Q2.30 短的“符號”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM