什么是背后的基本原理(X%64)==(X放大器; 63)?放大器、基本原理

2023-09-12 21:23:30 作者:没有梦想、何必远方

可能重复:   位运算和代替模运算

有人能解释,使双方的前pressions当量的理由是什么?我知道这只能是因为64是二的幂,但我怎么能在逻辑上或数学上的分工去按位和?

Can someone explain the rationale that makes both expressions equivalents? I know it only works because 64 is a power of two, but how can I logically or mathematically go from division to bitwise and?

推荐答案

操作 X%64 返回余数时, X 是64,这(假定X> 0)必须是一个介于0和63。让我们来看看这二分:

The operation x % 64 returns the remainder when x is divided by 64, which (assuming x>0) must be a number between 0 and 63. Let's look at this in binary:

63 月 = 0011 1111 B 64 月 = 0100 0000 B

63dec = 0011 1111b 64dec = 0100 0000b

您可以看到,64的倍数的二进制再presentation必须有6个零结束。因此,当除以64任何数目的余数是原始数,与所有的除了最右边的6那些除去位

You can see that the binary representation of any multiple of 64 must end with 6 zeroes. So the remainder when dividing any number by 64 is the original number, with all of the bits removed except for the 6 rightmost ones.

如果你走位与一个数字63,结果是完全相同的6位。

If you take the bitwise AND of a number with 63, the result is exactly those 6 bits.