签名&安培;无符号整数乘法 [英] Signed & unsigned integer multiplication

查看:147
本文介绍了签名&安培;无符号整数乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定点数学我用了很多16bit的信号,并与32位中间结果进行乘法运算。例如:

In fixed point math I use a lot of 16bit signals and perform multiplication with 32bit intermediate results. For example:

int16_t a = 16384; //-1.0q14  or 1.0*2^14
int16_t b = -24576; // -1.4q14  or 1.4*2^14
int16_t c; // result will be q14

c = (int16_t)(((int32_t)a * (int32_t)b)>>14);

让我们说是Q14号码,然后用c具有相同的比例为b。

Lets say a is a q14 number then c with have the same scaling as b.

这是很好,适用于未签名以及签名的算法。

This is fine and works for unsigned as well as signed arithmetic.

现在的问题是:如果我是混合类型会发生什么?例如,如果我知道乘数一总是将范围从0.0到1.0,它是诱人,使其一个unsigned int Q15获得precision的额外位(和改变移位数为15)。但是,我永远无法理解,如果你试图在C繁殖符号和无符号数,并避免它发生了什么。在ASM我不记得那里是一个乘法指令,将混合类型的工作,在任何体系,所以即使如果C做正确的事我不知道它会产生有效的code。

The question is: What happens if I were to mix types? For example if I know the multiplier "a" is always going to range from 0.0 to 1.0, it is tempting to make it an unsigned int q15 to get the extra bit of precision (and change the shift count to 15). However, I never understood what happens if you try to multiply signed and unsigned numbers in C and have avoided it. In ASM I don't recall there being a multiply instruction that would work with mixed types on any architecture, so even if C does the right thing I'm not sure it would generate efficient code.

我应该继续我未签署混合在固定点code无符号类型的做法?还是这个工作的很好?

Should I continue my practice of not mixing signed an unsigned types in fixed point code? Or can this work nicely?

推荐答案

<一个href=\"http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe\">This帖子关于签署乘以和无符号整数时会发生什么会谈。简短的回答是,只要是同一等级(大小),一签的是隐式类型强制转换为无符号。

This post Talks about what happens when multiplying signed and unsigned integers. Short answer is, as long as they are the same rank (size), a signed is implicitly typecast to unsigned.

只要你理解了类型转换规则,或者使用显式类型转换,你也明白类型转换的影响(无论语言,你是编程中)从符号到无符号(负数会产生,可能会出现什么为乱码时,类型强制转换为符号值),那么就应该是没有问题的混合符号和无符号类型。

As long as you understand the typecasting rules (of whatever language you are programming in), or use explicit typecasting, and you also understand the implications of typecasting from signed to unsigned (a negative number will produce what may appear as gibberish when typecasted to a signed value), then there should be no issue mixing signed and unsigned types.

这篇关于签名&安培;无符号整数乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆