高效(按位)除以 24
对于没有整数除数(也没有乘数)的嵌入式平台进行编码,是否有一种快速方法来执行“除以 24”?
乘以 24 很简单,
int a;
int b = (a << 4) + (a << 3); // a*16 + a*8
但是除法呢?这是一个非常简单的除数,只设置了两位?
Coding for an embedded platform with no integer divisor (nor multiplier), is there a quick way to perform a 'divide by 24'?
Multiply by 24 is simply
int a;
int b = (a << 4) + (a << 3); // a*16 + a*8
But division? It's a really simple divisor, with only two bits set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您可以使用
24=8*3
这一事实,因此您可以再次使用移位除以8
:a / 8 == a >>> 3.
。然后您必须将结果除以3
。关于如何有效地做到这一点的讨论可以在此处找到。当然,如果您使用 c(或任何其他高级语言)进行编码,那么首先简单地查看编译器输出可能是值得的,编译器可能已经为此提供了一些技巧。Well first of all you can use the fact that
24=8*3
, so you can divide by8
using shifting once again:a / 8 == a >> 3
. Afterwards you have to divide the result by3
. A discussion about how to do that efficiently can be found here. Of course if you are coding inc
(or any other higher level language really), it might be worthwile to simply look at the compileroutput first, it is possible that the compiler already has some tricks for this.如果您不需要结果是位精确的,那么您可以考虑乘以 1/24:
当然,如果您的平台没有硬件乘法器,那么您将需要优化该乘法。事实证明,(65536 / 24) 大约等于 2730,即二进制的 101010101010。这样乘法可以通过 3 次移位和加法来实现。
If you don't need the result to be bit-exact, then you could consider multiplying by 1/24:
Of course, if your platform doesn't have a hardware multiplier, then you will need to optimise that multiplication. As it turns out, (65536 / 24) is approximately equal to 2730, which is 101010101010 in binary. So that multiply can be achieved with 3 shifts and adds.