views:

40

answers:

2

Is there any clever way to mix two bit sequences in such way that bits from first sequence will be on odd places, and bits from second sequence will be on even places.
Both sequences are no longer than 16b so output will fit into 32bit integer.

Example:

First sequence  : 1   0   0   1   0   0  
Second sequence :   1   1   1   0   1   1  
Output          : 1 1 0 1 0 1 1 0 0 1 0 1

I thought about making integer array of size 2^16 and then the output would be:

arr[first] << 1 | arr[second]
+1  A: 

in C#:

public Int32 Mix(Int16 b1, Int16 b2)
{
  Int32 res = 0;
  for (int i=0; i<16; i++)
  {
    res |= ((b2 >> i) & 1) << 2*i;
    res |= ((b1 >> i) & 1) << 2*i + 1;
  }
  return res;
}
PierrOz
I know how to do it using for loop...
Tomek Tarczynski
sorry, it was not mentioned in your question... :)
PierrOz
+1  A: 

Have a look at http://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableLookup This page lists the obvious (for loop) and 3 optimized algorithms. Neither one is particularly simple but without testing I'd guess they are considerably faster than a loop.

doublep