title: What is the preferred way to take the modulus by a power of 2 of an int in Python
body: <p>Imagine that you have some counter or other data element that needs to be stored in a field of a binary protocol. The field naturally has some fixed number <em>n</em> of bits and the protocol specifies that you should store the <em>n</em> least significant bits of the counter, so that it wraps around when it is too large. One possible way to implement that is actually taking the modulus by a power of two:</p>
  
  <pre><code>field_value = counter % 2 ** n
  </code></pre>
  
  <p>But this certainly isn't the most efficient way and maybe not even the easiest to understand, taking into account that the specification is talking about the <em>least significant bits</em> and does not mention a modulus operation. Thus, investigating alternatives is appropriate. Some examples are:</p>
  
  <pre><code>field_value = counter % (1 &lt;&lt; n)
  field_value = counter &amp; (1 &lt;&lt; n) - 1
  field_value = counter &amp; ~(-1 &lt;&lt; 8)
  </code></pre>
  
  <p>What is the way preferred by experienced Python programmers to implement such a requirement trying to maximize code clarity without sacrificing too much performance?</p>
  
  <p>There is of course no right or wrong answer to this question, so I would like to use this question to collect all the reasonable implementations of this seemingly trivial requirement. An answer should list the alternatives and shortly describe in what circumstance what alternative would preferably be used.</p>