Arduino/C++ byte manipulation
Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:

int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits &amp; 0x01) retval |= 0x001;
   if (old_bits &amp; 0x02) retval |= 0x002;
   if (old_bits &amp; 0x04) retval |= 0x004;
   if (old_bits &amp; 0x08) retval |= 0x008;
   if (new_bits &amp; 0x01) retval |= 0x010;
   if (old_bits &amp; 0x10) retval |= 0x020;
   if (old_bits &amp; 0x20) retval |= 0x040;
   if (old_bits &amp; 0x40) retval |= 0x080;
   if (new_bits &amp; 0x02) retval |= 0x100;
   if (old_bits &amp; 0x80) retval |= 0x200;
   if (new_bits &amp; 0x04) retval |= 0x400;
   if (new_bits &amp; 0x08) retval |= 0x800;
   return retval;
}


On most microprocessors, this will compile into just a few instructions per statement.

This is also arguably more maintainable than a complex series of shift and mask operations.