English 中文(简体)
为什么(x和3)与(x mo4)相同?
原标题:Why is ( x & 3 ) identical to ( x mod 4 )?

我发现了一些来源代码,其中作者似乎使用双向代码&的操作者而不是%的操作者。 但是,我尝试了<代码>x & 4。 该数值与<代码>x% 5相同。

问题回答

这只是行使权力。

一般而言:

x MOD 2^n

相当于:

x AND (2^n - 1)

请注意,这只能适用于<代码>x >=0,视您对<代码>MOD的定义而定;<0。


为了理解why这一工程,在进行分类后,审议国防部究竟是什么——它只是remainder。 如果划分为2英亩,我们实际上只是将双轨价值权转嫁给一旁,并抛弃任何转移的低级定比值,例如8倍的双位数。

a b c d e f g h

如果我们分四 = 2^2,那么我们就把右面改为两条轨道:

0 0 a b c d e f

其余部分(g h)由于分类账而被撤销。

如果我们想知道其余部分,我们就只能提取借方代码。 采用<代码>0 0 0 0 0 1:

    a b c d e f g h
AND 0 0 0 0 0 0 1 1
  = 0 0 0 0 0 0 g h

注意价值3,一般情况下仅为2^n-1。

让我们用一些实际数字来尝试。 赞同我们计算42/4,获得报价和其余部分:

42 = 0 0 1 0 1 0 1 0

为了让引人思考,我们分两点:

  42 / 4 (decimal)
= 0 0 1 0 1 0 1 0 >> 2
= 0 0 0 0 1 0 1 0
= 10 (decimal)

  42 MOD 4 (decimal)
= 0 0 1 0 1 0 1 0 AND 0 0 0 0 0 0 1 1
= 0 0 0 0 0 0 1 0
= 2 (decimal)

So 42/4 = 10 remainder 2.

答案非常简单,试图以双手方式思考。

0000 = 0 AND 11 = 0000 = 0
0001 = 1 AND 11 = 0001 = 1
0010 = 2 AND 11 = 0010 = 2
0011 = 3 AND 11 = 0011 = 3
0100 = 4 AND 11 = 0000 = 0
0101 = 5 AND 11 = 0001 = 1
0110 = 6 AND 11 = 0010 = 2
0111 = 7 AND 11 = 0011 = 3

... and so on.

This have the same result as reminder (% is remainder, formally, not modulus). It works only with powers of 2 and only for zero and positive numbers.





相关问题
Maths in LaTex table of contents

I am trying to add a table of contents for my LaTex document. The issue I am having is that this line: subsubsection{The expectation of (X^2)} Causes an error in the file that contains the ...

Math Overflow -- Handling Large Numbers

I am having a problem handling large numbers. I need to calculate the log of a very large number. The number is the product of a series of numbers. For example: log(2x3x66x435x444) though my actual ...

Radial plotting algorithm

I have to write an algorithm in AS3.0 that plots the location of points radially. I d like to input a radius and an angle at which the point should be placed. Obviously I remember from geometry ...

Subsequent weighted algorithm for comparison

I have two rows of numbers ... 1) 2 2 1 0 0 1 2) 1.5 1 0 .5 1 2 Each column is compared to each other. Lower values are better. For example Column 1, row 2 s value (1.5) is more ...

热门标签