[英]Multiplication of two 32 bit numbers using only 8 bit numbers
I saw this interview question online and can't find a good method other than the usual additive methods. 我在网上看到了这个面试问题,除了通常的加法方法外找不到其他好的方法。 Any suggestions if this can be done quicker using some bitshift / recursion or something similar ?
有什么建议可以使用某些移位/递归或类似方法更快地完成?
Bitshifting would be natural part of a solution. 移位将是解决方案的自然组成部分。
To multiply a value a by an eight-bit value b , for each 1 bit in b , add up all the values of a multiplied by b with all other bits set to 0. For example, a * 10100001 = a * 10000000 + a * 00100000 + a * 00000001
. 由八比特值b相乘的值的 ,对于b各自1位,加起来的所有值乘以b相设定为0。例如,所有其它位
a * 10100001 = a * 10000000 + a * 00100000 + a * 00000001
。
Taking this further, suppose we want to multiply 11001011
by 0010000
, this is 11001011(bin) << 4(dec)
. 以这进一步,假设我们要乘以
11001011
的0010000
,这是11001011(bin) << 4(dec)
Doing this on an eight-bit value gives you 10110000
. 对一个八位的值执行此操作将为您提供
10110000
。 You have also lost (8-4)=4
bits from the beginning. 您还从一开始就丢失了
(8-4)=4
位。 Hence you would also want to do 11001011(bin) >> 4(dec)
to get 00001100
as a carry into the next "8-bit column" (assuming that we are using 8 columns to represent a 64-bit answer). 因此,您还想执行
11001011(bin) >> 4(dec)
来获得00001100
作为进位到下一个“ 8位列”中(假设我们使用8列来表示64位答案)。
Recursion would not really be necessary. 递归实际上不是必需的。 All you'd need is a loop through the 4 bytes of the first 32-bit number, with another loop through the 4 bytes of the second number inside, multiplying each pair of bytes together in turn and adding it to your solution.
您所需要做的就是循环遍历第一个32位数字的4个字节,并在内部循环遍历第二个数字的4个字节,依次将每对字节相乘,并将其添加到您的解决方案中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.