【发布时间】:2020-03-13 07:39:59
【问题描述】:
我有一个非常基本的问题。在我的程序中,我正在对两个定点数进行乘法运算,如下所示。我的输入是 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.
我哪里出错了?我需要了解任何其他概念吗?
【问题讨论】:
-
也许您需要了解更多关于计算机如何处理负数的知识,更具体地说是关于two's complement?假设
int是32 位类型(最常见),那么1 << 31将是一个非常大的负数(-2147483648)。 -
@Someprogrammerdude..感谢您的回复。因此,您说最大正值为 (1
-
合适的答案可能在以下链接stackoverflow.com/questions/41717188/…
-
@rkc 是正确的
标签: c rounding multiplication fixed-point