Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This only works for powers of 2.</p> <p>In general:</p> <pre><code>x MOD 2^n </code></pre> <p>is equivalent to:</p> <pre><code>x AND (2^n - 1) </code></pre> <p>Note also that this may be true only for <code>x &gt;= 0</code>, depending on your definition of <code>MOD</code> for <code>x &lt; 0</code>.</p> <hr> <p>To understand <em>why</em> this works, consider what MOD really is - it's just the <em>remainder</em> after performing integer division. In the case of a division by 2^n, we are effectively just shifting a binary value right by n bits and discarding any low order bits that get shifted out, e.g. for an 8 bit binary number</p> <pre><code>a b c d e f g h </code></pre> <p>if we divide by 4 = 2^2 then we shift right by 2 bits:</p> <pre><code>0 0 a b c d e f </code></pre> <p>The remainder (<code>g h</code>) has been thrown away as a result of the integer division.</p> <p>If we wanted to know the remainder then we could just extract the bits <code>g h</code> by applying a mask of <code>0 0 0 0 0 0 1 1</code>:</p> <pre><code> 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 </code></pre> <p>Note that the has has value 3, which in the general case is just 2^n - 1.</p> <p>Let's try this with some real numbers. Suppose we want to calculate 42 / 4 and get both the quotient and the remainder:</p> <pre><code>42 = 0 0 1 0 1 0 1 0 </code></pre> <p>To get the quotient we shift right by 2 bits:</p> <pre><code> 42 / 4 (decimal) = 0 0 1 0 1 0 1 0 &gt;&gt; 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) </code></pre> <p>So 42/4 = 10 remainder 2.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload