"Beginning C from Novice to Professional"中右移用法的误区

Misunderstanding of the usage of right shift in "Beginning C from Novice to Professional"

我不知道这个右移怎么等于0: 我明白移位是如何工作的,但为什么作者说它在二进制零中等于而在十进制中却有不同的结果?二进制零和十进制零不一样吗?

0000

还有它怎么等于二进制零?

unsigned int value = 65372U;

As a binary value in a 2-byte variable, this is:

1111 1111 0101 1100

Suppose you now execute the following statement:

unsigned int result = value >> 2; /* Shift right two bits */

The bits in value will be shifted two places to the right, introducing zeros at the left end, and the resultant value will be stored in result. In binary this will be 0, which is the decimal value 16343.

0011 1111 1101 0111

你的假设是正确的。二进制 0 与整数 0 相同。这本书往好了说是印刷错误,往坏了说是完全错误。不过它的例子似乎还可以。

此外,郑重声明,二进制 0 就是您所期望的:

0000 0000 0000 0000

0011 1111 1101 0111 不等于 0。

实践中的位移位涉及逐字移动位 N 个位置,因此对于 2 的位移:

10101101
||||||
 \\\
  \\\
  vvvvvv
00101011

数学上右移一位相当于除以二,而左移相当于乘以二。您会看到有时会使用这种优化,因为移位通常比乘法快得多。

就像小数除以十的任意次方很简单,你只需要删除一定数量的数字或移动小数位。