user7865: Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.
Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.
eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.
01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1
What would be the most efficient way to accomplish this?

user614: 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 & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 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.

7865: <p>Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.</p>

<p>Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.</p>

<p>eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.</p>

<p>01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1</p>

<p>What would be the most efficient way to accomplish this?</p>
 614: <p>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:</p>

<pre><code>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;
}
</code></pre>

<p>On most microprocessors, this will compile into just a few instructions per statement.</p>

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