title: Overwriting a range of bits in an integer in a generic way
body: <p>Given two integers X and Y, I want to overwrite bits at position P to P+N.</p>
  
  <p>Example:</p>
  
  <pre><code>int x      = 0xAAAA; // 0b1010101010101010
  int y      = 0x0C30; // 0b0000110000110000
  int result = 0xAC3A; // 0b1010110000111010
  </code></pre>
  
  <p>Does this procedure have a name?</p>
  
  <p>If I have masks, the operation is easy enough:</p>
  
  <pre><code>int mask_x =  0xF00F; // 0b1111000000001111
  int mask_y =  0x0FF0; // 0b0000111111110000
  int result = (x &amp; mask_x) | (y &amp; mask_y);
  </code></pre>
  
  <p>What I can't quite figure out is how to write it in a generic way, such as in the following generic C++ function:</p>
  
  <pre><code>template&lt;typename IntType&gt;
  IntType OverwriteBits(IntType dst, IntType src, int pos, int len) {
  // If:
  // dst    = 0xAAAA; // 0b1010101010101010
  // src    = 0x0C30; // 0b0000110000110000
  // pos    = 4                       ^
  // len    = 8                ^-------
  // Then:
  // result = 0xAC3A; // 0b1010110000111010
  }
  </code></pre>
  
  <p>The problem is that I cannot figure out how to make the masks properly when all the variables, including the width of the integer, is variable.</p>
  
  <p>Does anyone know how to write the above function properly?</p>