本文介绍了在C位移位乘法不使用2的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过使用36位移执行乘法?是不是只能通过2的幂乘?例如:

How can I perform multiplication by 36 using bit-shifting? Isn't it only possible to multiply by powers of 2? For example:

unsigned x = 4; // binary 00000000 00000000 00000000 00001000
unsigned y = x << 3; // multiply by 8, resulting in binary 00000000 ... 00100000

谢谢!

推荐答案

您不能用2的无动力由单独位移繁殖。

You can't multiply by a non-power of 2 by bit shifting alone.

但是你可以使用分解加法和乘法:

But you can break it down using addition and multiplication:

x * 36 = x * (32 + 4)
       = (x * 32) + (x * 4)

由于 32 4 2 的权力( 2 ^ 5 2 ^ 2 分别),您可以执行这些作为单独的变化和增加的结果。

Since 32 and 4 are powers of 2 (2^5 and 2^2 respectively), you can perform those as separate shifts and add the results.

这篇关于在C位移位乘法不使用2的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 05:06