0

我从中找到这段代码的书使用它找出某个范围内的偶数。“与”运算符的作用与模运算符完全一样,在奇数的情况下返回 1,在偶数的情况下返回零。

4

1 回答 1

2
Let's pick a number: 345 looks nice

In binary: ‭000101011001‬ (I used the windows calculator to give me this, 
                         rather than get into anything deeper)

Now if we AND it with 1 (000000000001 in binary), that's a bit masking 
operation. When we bit mask we compare the truth of the numbers in the 
same column, and only record a 1 in that column for the result when both 
the number above are 1:

    ‭000101011001‬
AND 000000000001  
    ^
    0 and 0 is 0

    ‭000101011001‬
AND 000000000001  
     ^
     0 and 0 is 0

    ‭000101011001‬
AND 000000000001  
      ^
      0 and 0 is 0

    ‭000101011001‬
AND 000000000001  
       ^
       1 and 0 is 0

...

    ‭000101011001‬
AND 000000000001  
               ^
               1 and 1 is 1



This means the result is:


    ‭000101011001‬
AND 000000000001   
=   000000000001 (i.e. the result of masking 345 with 1 is 1)

So this number had a binary 1 at the right hand side of its representation, and it's an ODD
number. All odd numbers have a 1 at the right hand side of their representation:

  1: 0001
  3: 0011
  5: 0101
  7: 0111
  9: 1001

Masking any of them with 1 will reliably produce a result of 1,
and we can hence check the result to be 1 to know the input number was odd
...

The opposite is true for even numbers, they always finish with a 0. Take 344 for example:

 344: ‭0001010110010 <--it's like 345, except one less
 AND  0000000000001
   =  0000000000000 <-- the result is 0. 346 is EVEN. Even numbers always have
                        a 0 in the right hand side of their binary representation


于 2020-03-16T16:49:53.727 回答