简体   繁体   English

使用有限的按位运算符将无符号整数乘以10

[英]Multiplying an unsigned integer by 10 with limited bitwise operators

This is a question on a practice exam: 这是一个关于练习考试的问题:

Write a function that multiples the argument by 10. You may only use these operators: << - & ^ and the only allowed constants to shift by are 1 2 4 8 16. 编写一个将参数乘以10的函数。您只能使用这些运算符:<< - &^和唯一允许的常数移位为1 2 4 8 16。

The function prototype is: 功能原型是:

unsigned int(unsigned int x); unsigned int(unsigned int x);

We were given a solution, which was: 我们得到了一个解决方案,即:

unsigned int(unsigned int x) { 
    return (x << 4) - (x << 2) - (x << 1); 
} 

I understand that it works, and that it does so by subtracting multiples of ten from an integer. 我知道它有效,并且它通过从整数中减去10的倍数来实现。 I don't understand why it works, and would like to understand the process of how to arrive at this answer. 我不明白为什么它有效,并想了解如何得出这个答案的过程。

Thanks in advance for any answers! 提前感谢您的任何答案!

(x << 4) is essentially x * 16 , (x << 2) is x * 4 , and (x << 1) is x * 2 . (x << 4)基本上是x * 16(x << 2)x * 4(x << 1)x * 2 Therefore, 16x - 4x - 2x = 10x . 因此, 16x - 4x - 2x = 10x

As for why (x << 4) is equal to x * 16 , it's because of the binary representation. 至于为什么(x << 4)等于x * 16 ,这是因为二进制表示。 Let's take 10 in binary (only 8 bits shown for clarity; there's actually a bunch more zeroes to the left): 让我们用二进制10(为清晰起见只显示8位;左边实际上有一堆更多的零):

00001010

Now let's shift left 4 spaces: 现在让我们左转4个空格:

10100000

That's 160. 那是160。

A way of thinking of this is that when you add a zero in base ten (ie 10 -> 100), you're multiplying by 10. When you add a zero in base two, you're multiplying by 2. Therefore, shifting 4 spaces (and therefore adding 4 zeroes) multiplies by 2*2*2*2 = 16 . 一种思考方式是,当你在基数十(即10 - > 100)中加零时,你乘以10.当你在基数2中加零时,你乘以2.因此,转移4个空格(因此增加4个零)乘以2*2*2*2 = 16

x << 1 = x * 2. x << 1 = x * 2。

x << 2 = x * 4. x << 2 = x * 4。

x << 4 = x * 16. x << 4 = x * 16。

16 - 4 - 2 = 10. 16 - 4 - 2 = 10。

You could also use: 你也可以使用:

x << 3 = x * 8 x << 3 = x * 8

But 8 + 2 = 10, so you could use (x << 2 << 1) + (x << 1). 但是8 + 2 = 10,所以你可以使用(x << 2 << 1)+(x << 1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM