开发者

Mix of two bit sequences

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  开发者_Go百科 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]


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜