高效(按位)除以 24

发布于 2024-12-20 12:48:25 字数 194 浏览 3 评论 0原文

对于没有整数除数(也没有乘数)的嵌入式平台进行编码,是否有一种快速方法来执行“除以 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哎呦我呸! 2024-12-27 12:48:26

首先,您可以使用 24=8*3 这一事实,因此您可以再次使用移位除以 8a / 8 == a >>> 3.。然后您必须将结果除以3。关于如何有效地做到这一点的讨论可以在此处找到。当然,如果您使用 c(或任何其他高级语言)进行编码,那么首先简单地查看编译器输出可能是值得的,编译器可能已经为此提供了一些技巧。

Well first of all you can use the fact that 24=8*3, so you can divide by 8 using shifting once again: a / 8 == a >> 3. Afterwards you have to divide the result by 3. A discussion about how to do that efficiently can be found here. Of course if you are coding in c (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.

£烟消云散 2024-12-27 12:48:25

如果您不需要结果是位精确的,那么您可以考虑乘以 1/24:

uint16_t a = ...;

uint32_t b = (uint32_t)a * (65536L / 24);

uint16_t c = b / 65536;

当然,如果您的平台没有硬件乘法器,那么您将需要优化该乘法。事实证明,(65536 / 24) 大约等于 2730,即二进制的 101010101010。这样乘法可以通过 3 次移位和加法来实现。

If you don't need the result to be bit-exact, then you could consider multiplying by 1/24:

uint16_t a = ...;

uint32_t b = (uint32_t)a * (65536L / 24);

uint16_t c = b / 65536;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文