title: Integer subtraction with wrap around for N bits
body: <p>Basically, the behavior you get when overflowing integers with subtraction, but for a given number of bits. The obvious way, assuming a <strong>signed</strong> integer:</p>
  
  <pre><code>template &lt;int BITS&gt;
  int sub_wrap(int v, int s) {
    int max = (1&lt;&lt;(BITS));
    v -= s;
    if (v &lt; -max) v += max*2;
    // or if branching is bad, something like:
    // v += (max*2) * (v &lt; -max)
    return v;
  }
  
  // For example subtracting 24 from -16 with 5 bit wrap,
  // with a range of -32, 31
  sub_wrap&lt;5&gt;(-16, 28); -&gt; 20
  </code></pre>
  
  <p>Is there a neat way of doing it that is less ugly and preferably faster than the one above?</p>
  
  <p>UPDATE: Sorry about the confusion. I thoughtlessly included the confusing notation of using the number of bits excluding the sigh bit. So in the above, replace 5 bits with 6 bits for a lot more sanity.</p>